New line in code is not working - c#

I'm using this code to send mails to my coworkers. The part at the mailMessage.Body, when I'm using "\r\n" is not working. Instead of showing the e-mail like this:
entity.PrimaryMeal.Title
entity.ScondaryMeal.Title
Porosine mund ta beni ketu: <> (this is in my language AL)
it is showing like this:
entity.PrimaryMeal.Title, entity.ScondaryMeal.Title. Porosine mund ta beni ketu: <>
What am I doing wrong?
private void SendMail(string MailReciever)
{
Configuration configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettingsSectionGroup = (MailSettingsSectionGroup)configuration.GetSectionGroup("system.net/mailSettings");
string MailSender = mailSettingsSectionGroup.Smtp.From;
string Username = mailSettingsSectionGroup.Smtp.Network.UserName;
string UserPassword = mailSettingsSectionGroup.Smtp.Network.Password;
string SmtpServer = mailSettingsSectionGroup.Smtp.Network.Host;
int Port = mailSettingsSectionGroup.Smtp.Network.Port;
bool UseSsl = mailSettingsSectionGroup.Smtp.Network.EnableSsl;
bool UseDefaultCredentials = mailSettingsSectionGroup.Smtp.Network.DefaultCredentials;
using (SmtpClient smtpClient = new SmtpClient())
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.To.Add(MailReciever);
mailMessage.From = new MailAddress(MailSender);
mailMessage.Subject = ConfigurationManager.AppSettings["NewMailSubject"];
smtpClient.Host = SmtpServer;
smtpClient.UseDefaultCredentials = UseDefaultCredentials;
smtpClient.Port = Port;
smtpClient.Credentials = new NetworkCredential(Username, UserPassword);
smtpClient.EnableSsl = UseSsl;
#region MailMessageBody
var entity = Factory.Orders.List(item => item.OrderDate == DateTime.Today).ToList().FirstOrDefault();
if (entity.SecondaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
else if (entity.TertiaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ",\r\n" + entity.SecondaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
else
{
mailMessage.Body = entity.PrimaryMeal.Title + ",\r\n" + entity.SecondaryMeal.Title + ",\r\n" + entity.TertiaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
#endregion
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
}
}

mailMessage.IsBodyHtml = true;
You are sending your email as Html (which ignores raw line breaks), you should add the <br> tag instead (or work with paragraphs).
if (entity.SecondaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ".<br>Porosine mund ta beni ketu: http://10.200.30.11:8888";
}
else if (entity.TertiaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ",<br>" + entity.SecondaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
else
{
mailMessage.Body = entity.PrimaryMeal.Title + ",<br>" + entity.SecondaryMeal.Title + ",<br>" + entity.TertiaryMeal.Title + ".<br>Porosine mund ta beni ketu: http://10.200.30.11:8888";
}

I think its better to send HTML mail. That means you need to put <br/> instead of \r\n and set Message body type as HTML.

Related

Need to send emails to multiple users

I have developed a simple alert system which will read a table in SQL and send emails accordingly. There are Usernames, Email Addresses, Messages to be sent in that SQL table. The system will read the table every 20 minutes and will send emails to the users according to their respective email address. But at the moment the system sends emails to one user only. I want to further develop this system to send emails to multiple users when one set has finished. I do not have an idea how to do this. Is there anyone who can help me with this. Code snippet would be more helpful to understand.
Below is the SQL table template
Name | Email | Factory| AlertTime| Description
User1 | user1#mydomain.com | FAC1 | 01:50:00 | UserMessage1
User1 | user1#mydomain.com | FAC2 | 01:50:00 | UserMessage2
User1 | user1#mydomain.com | FAC3 | 03:00:00 | UserMessage3
User2 | user2#mydomain.com | FAC1 | 01:20:00 | UserMessage1
User2 | user2#mydomain.com | FAC2 | 01:50:00 | UserMessage2
User2 | user2#mydomain.com | FAC3 | 03:00:00 | UserMessage3
User3 | user3#mydomain.com | FAC1 | 01:20:00 | UserMessage1
User3 | user3#mydomain.com | FAC2 | 01:50:00 | UserMessage2
User3 | user3#mydomain.com | FAC3 | 03:00:00 | UserMessage3
Below is my C# cord
using System;
using System.Timers;
using System.Windows.Forms;
using System.Net.Mail;
using System.Data;
using System.Speech.Synthesis;
using System.Collections.Generic;
namespace Alerts
{
public partial class frmAlerts : Form
{
SpeechSynthesizer speechSynthesizerObj;
Common ComMsg = new Common();
DataSet DatMsg = new DataSet();
AlertException error = new AlertException();
List<string> AlertList = new List<string>();
string ToName;
string ToEmail;
string TotMsg;
public frmAlerts()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
}
private void frmAlerts_Load(object sender, EventArgs e)
{
try
{
System.Timers.Timer timer = new System.Timers.Timer(20 * 60 * 1000);
timer.Elapsed += new ElapsedEventHandler(SendAlerts);
timer.Start();
}
catch (Exception ex)
{
MessageBox.Show("Error in application Load: " + ex.Message);
}
}
public void SendAlerts(object source, ElapsedEventArgs e)
{
try
{
DatMsg = ComMsg.ReturnDataSet("SELECT RptAlertRecipient.Name, RptAlertRecipient.Email, RptAlerts.Factory, RptAlerts.AlertTime, RptAlerts.Description " +
"FROM RptAlerts " +
"INNER JOIN RptAlertTypes ON RptAlerts.AlertTypeID = RptAlertTypes.ID " +
"INNER JOIN RptAlertType_RecipientMapping ON RptAlertTypes.ID = RptAlertType_RecipientMapping.AlertTypeID " +
"INNER JOIN RptAlertRecipient ON RptAlertType_RecipientMapping.AlertRecipientID = RptAlertRecipient.ID " +
"WHERE RptAlertRecipient.Name= 'User1' " +
"ORDER BY RptAlertRecipient.Name ASC");
for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
TotMsg = (j + 1).ToString();
}
string to = ToEmail;
string from = "helpdesk#mydomain.com";
string subject = "Alert In Time : You Have "+TotMsg+ " Alerts";
string msgBody = "Dear " + ToName + ",<br/><br/>";
msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
msgBody += string.Join("<br/>", AlertList);
msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "password");
clnt.Send(msg);
}
catch (Exception ex)
{
error.ExceptionMessage = ex.ToString();//gets the exception message to a separate class
speechSynthesizerObj = new SpeechSynthesizer();
speechSynthesizerObj.SpeakAsync(ex.Message);//Speaks the Error
}
}
}
}
I suppose your current code only sends a mail to the last user in the list?
You will have to include the code that generates and sends the mail in your for loop.
for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
TotMsg = (j + 1).ToString();
string to = ToEmail;
string from = "helpdesk#mydomain.com";
string subject = "Alert In Time : You Have "+TotMsg+ " Alerts";
string msgBody = "Dear " + ToName + ",<br/><br/>";
msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
msgBody += string.Join("<br/>", AlertList);
msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "password");
clnt.Send(msg);
}
I found a solution for that. I did some changes to the code and now it is working the way I wanted it to happen. Below is my code. Thank you everyone for your help.
using System;
using System.Data;
using System.Timers;
using System.Net.Mail;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Collections.Generic;
namespace Alerts
{
public partial class frmAlerts : Form
{
SpeechSynthesizer speechSynthesizerObj;
Common ComMsg = new Common();
DataSet DatMsg = new DataSet();
DataSet DatNames = new DataSet();
AlertException error = new AlertException();
List<string> AlertList = new List<string>();
string ToName;
string ToEmail;
string TotMsg;
string _Name;
public frmAlerts()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
}
private void frmAlerts_Load(object sender, EventArgs e)
{
try
{
System.Timers.Timer timer = new System.Timers.Timer(20 * 60 * 1000);
timer.Elapsed += new ElapsedEventHandler(SendAlerts);
timer.Start();
}
catch (Exception ex)
{
MessageBox.Show("Error in application Load: " + ex.Message);
SendtoAdmin();
}
}
public void SendAlerts(object source, ElapsedEventArgs e)
{
try
{
DatNames = ComMsg.ReturnDataSet("SELECT Name FROM RptAlertRecipient ORDER BY Name DESC");
for (int i = 0; i < DatNames.Tables[0].Rows.Count; i++)
{
_Name = DatNames.Tables[0].Rows[i].ItemArray.GetValue(0).ToString();
DatMsg = ComMsg.ReturnDataSet("SELECT RptAlertRecipient.Name, RptAlertRecipient.Email, RptAlerts.Factory, RptAlerts.AlertTime, RptAlerts.Description " +
"FROM RptAlerts " +
"INNER JOIN RptAlertTypes ON RptAlerts.AlertTypeID = RptAlertTypes.ID " +
"INNER JOIN RptAlertType_RecipientMapping ON RptAlertTypes.ID = RptAlertType_RecipientMapping.AlertTypeID " +
"INNER JOIN RptAlertRecipient ON RptAlertType_RecipientMapping.AlertRecipientID = RptAlertRecipient.ID " +
"WHERE RptAlertRecipient.Name ='" + _Name + "'" +
"ORDER BY RptAlertRecipient.Name DESC");
for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
TotMsg = (j + 1).ToString();
}
string to = ToEmail;
string from = "helpdesk#mydomain.com";
string subject = "Alert In Time : You Have " + TotMsg + " Alerts";
string msgBody = "Dear " + ToName + ",<br/><br/>";
msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
msgBody += string.Join("<br/>", AlertList);
msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "password");
clnt.Send(msg);
AlertList.Clear();
}
}
catch (Exception ex)
{
error.ExceptionMessage = ex.ToString();
speechSynthesizerObj = new SpeechSynthesizer();
speechSynthesizerObj.SpeakAsync(ex.Message);//Speaks the Error
SendtoAdmin();
}
}
#region SendMails
protected void SendtoAdmin()
{
//Send mail to Admin
string to = "admin#mydomain.com";
string from = "helpdesk#mydomain.com";
string subject = "System Failure";
string msgBody = "Dear Admin,<br/><br/>System Failure in Alert System.<br/>Please Attend Immediately.<br/>"+ error.ExceptionMessage + "<br/><br/>Regards<br/>Sent By Alert System";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "sl#ithd");
clnt.Send(msg);
}
#endregion
}
}

Object variable or With block variable not set while sending attachment in email in asp.net

I need to send attachment with email. I used following code which gives below exceptions.
System.NullReferenceException: Object variable or With block variable
not set. at
Microsoft.VisualBasic.CompilerServices.Symbols.Container..ctor(Object
Instance) at
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object
Instance, Type Type, String MemberName, Object[] Arguments, String[]
ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack) at
dynamicPage.makeCustom_Click(Object sender, EventArgs e)
try {
generateRequestID();
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.To.Add("email.text");
mail.From = new MailAddress(personEmail.Text);
mail.Subject = "IDFC Bank BrandStore Product Customization Request";
mail.Body = "Request ID : " + Session["requestID"].ToString + "<br>Name : " + personName.Text + "<br>Contact : " + personContact.Text + "<br>Email : " + personEmail.Text + "<br>Department : " + Department.Text + "<br>Quantity : " + quantity.Text + "<br>Description : " + customDescription.Text + "<br>Timeline : " + customTimeline.Text + "<br>Product Link : " + Request.Url.AbsoluteUri + "";
if (artworkContainer.HasFile) {
string FileName = Path.GetFileName(artworkContainer.PostedFile.FileName);
mail.Attachments.Add(new Attachment(artworkContainer.PostedFile.InputStream, FileName));
}
mail.IsBodyHtml = true;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("you#yourdomain.com", "mypassword");
SmtpServer.Host = "relay-hosting.secureserver.net";
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
Response.Redirect("/customization-request-sent");
} catch (Exception ex) {
Response.Write(ex);
}

Email sending in aspnet identity

I wrote following method to send emails
public ActionResult SendEmail(UserData user)
{
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created with the Comp. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.UserEmail }, Request.Url.Scheme)) + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return View(user);
}
catch (Exception ex)
{
throw ex;
}
}
then I'm accessing above method in main controller like following
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
// await EmailController.Sendemail(sampleData);
var emailCntrl = new EmailController();
var sendEmail = emailCntrl.SendEmail(sampleData);
this is compiling without any compile times errors. but when I debug this I can see
in this line m.Body = str... I can see a error like this
because of that I'm getting an exception
Message = "Object reference not set to an instance of an object."
How can I solve this
You don't have Request, because you create just EmailController class. When controller factory creates controller for request it passes request data to Controller.Initialize Method.
Of course the best practice is to create EmailService as was mentioned above, but as answer for your question, you can make workaround. You can pass RequestContext of parent controller to EmailController in constructor and call Initialize. It's going to look like.
public EmailController()
{
}
public EmailController(RequestContext requestContext)
{
base.Initialize(requestContext);
}
And in your controller
var emailCntrl = new EmailController(this.ControllerContext.RequestContext);
var sendEmail = emailCntrl.SendEmail(sampleData);
You can also just set the ControllerContext
var emailCntrl = new EmailController(){ControllerContext = this.ControllerContext};
var sendEmail = emailCntrl.SendEmail(sampleData);
Well given that there was no request added to controller before calling action, it would be null.
There is no need for a controller there just to send the email.
Create a class/service to handle the email and pass in any dependencies
public class EmailService {
public UserData SendEmail(UserData user, string confirmationEmailUrl) {
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, confirmationEmailUrl + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return user;
}
catch (Exception ex)
{
throw ex;
}
}
}
And get the action from main controller
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
var confirmationEmailUrl = Url.Link("Default", new { Action = "ConfirmEmail", Controller = "Account", Token = sampleData.Id, Email = sampleData.UserEmail });
var emailService = new EmailService();
var user = emailService.SendEmail(sampleData, confirmationEmailUrl);

Clear Textboxs on submit

Hi i am looking to clear text boxs when a user clicks a button. However the code that i have is not working. Here is my code.
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();
m.Body = name.Text + Environment.NewLine + phone.Text + Environment.NewLine + email.Text + Environment.NewLine + message.Text;
m.IsBodyHtml = false;
m.To.Add("support#");
m.From = new System.Net.Mail.MailAddress(email.Text);
m.Subject = "Contact us form submisson";
m.Headers.Add("Reply-To", "your email account");
System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient();
s.UseDefaultCredentials = false;
s.Credentials = c;
s.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
s.EnableSsl = true;
s.Port = 587;
s.Host = "smtp.gmail.com";
s.Send(m);
lblCorrectCode.Text = "Contact Form Has been submited we will be in touch shortly";
name.Text = string.Empty;
phone.Text = string.Empty;
email.Text = string.Empty;
message.Text = string.Empty;
I surly hope you are not populate it in page load and not checking isPostBack
try
{
s.Send(m);
}
finally
{
lblCorrectCode.Text = "Contact Form Has been submited we will be in touch shortly";
name.Text = string.Empty;
phone.Text = string.Empty;
email.Text = string.Empty;
message.Text = string.Empty;
}

Unstable Sending of email in asp.net

I am building a ecommerce site and after a purchase is done, I want to send the buyer an email first before I commit my database changes but somehow, the send failure rate is about 25 - 30 percent. I am using hotmail current as a temp email account, not sure if it's hotmail's issue, anyway this is my code, any advice? Thanks:
Code:
MembershipUser u = Membership.GetUser(HttpContext.Current.User.Identity.Name);
AccountProfile usercustomProfile = new AccountProfile();
var p = usercustomProfile.GetProfile(u.UserName);
MailMessage mail = new MailMessage();
mail.To.Add(u.Email);
mail.IsBodyHtml = true;
mail.From = new MailAddress("XXX#hotmail.com");
mail.Subject = ("Purchase invoice" + ' ' + newOrder.OrderID);
string mailBodyHeader =
"<table border=0> <tr> <td>Product ID</td><td>Model Number</td><td>Model Name</td><td> Unit Cost</td> <td>Quantity</td><td>Price</td></tr>";
System.Text.StringBuilder bodyContent = new System.Text.StringBuilder();
double unitQtyPrice = 0;
double totalPrice = 0;
foreach (var cItem in cartList)
{
unitQtyPrice = cItem.Quantity * (double)cItem.UnitCost;
totalPrice += unitQtyPrice;
bodyContent.Append("<tr>");
bodyContent.Append("<td>");
bodyContent.Append(cItem.ProductID.ToString());
bodyContent.Append("</td>");
bodyContent.Append("<td>");
bodyContent.Append(cItem.ModelNumber.ToString());
bodyContent.Append("</td>");
bodyContent.Append("<td>");
bodyContent.Append(cItem.ModelName);
bodyContent.Append("</td>");
bodyContent.Append("<td>");
bodyContent.Append(Math.Round(cItem.UnitCost, 2));
bodyContent.Append("</td>");
bodyContent.Append("<td>");
bodyContent.Append(cItem.Quantity.ToString());
bodyContent.Append("</td>");
bodyContent.Append("<td>");
bodyContent.Append("$" + Math.Round(unitQtyPrice, 2));
bodyContent.Append("</td>");
bodyContent.Append("</tr>");
}
Math.Round(totalPrice, 2);
mail.Body = "Thanks you for shopping with XXX. Your purchase details are as follow:"
+ "<br><br>" + "Name:" + p.FirstName + p.LastName
+ "<br>" + "Mailing Address:" + p.MailingAddress
+ "<br>" + "Billing Address:" + p.BillingAddress
+ "<br>" + "Contact No.:" + p.Contact
+ "<br><br>" + mailBodyHeader + bodyContent.ToString() + "</table>"
+ "<br>" + "Total Price:" + "$" + totalPrice
+ "<br>" + "Additional / Special instructions:"
+ "<br>" + SInfo
+ "<br><br>" + "Please blah blah blah";
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //ssl must be enabled for Gmail
NetworkCredential credentials = new NetworkCredential("XXX#hotmail.com", "ABCDE");
client.Credentials = credentials;
//Sends a message to from if email is not deliverable
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
//Create the SMTPClient object and DO NOT specify the SMTP server name, it’s being pulled from config file
SmtpClient SMTPServer = new SmtpClient();
SMTPServer.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
try
{
client.Send(mail);
db.SaveChanges();
}
catch (SmtpException)
{
Server.Transfer("/CheckOutUnsuccessful.aspx", true);
}
}
return (true);
}
If you are using SQL Server on the backend you can set the database server up to handle the mail requests. The advantage of using SQL Server as opposed to ASP.NET code is the database can be configured to retry sending the messages several times on failure.
Here is a good resource on how to configure Database Mail: http://blog.sqlauthority.com/2008/08/23/sql-server-2008-configure-database-mail-send-email-from-sql-database/

Categories

Resources