Email formatting in code behind - c#

I need to send an email to a customer that has just completed a transaction but I am having some difficulties in drafting out the format in code behind, this is my code, apparently it's appearing as one straight line of text in the body of my mail, how can I format it in such a way it appears something like, any help is appreciated, thanks :
Thank you for shopping with us. Your purchase details are as follow:
Product ID Model Number Model Name Unit Cost Quantity ItemTotal
357 P1 AK47 Rifle(free 30 * 7.62) $2.99 1 2.99
362 XT3893 Mirage stealth tank $500000.99 1 500000.99
Total:$500002.99
This is my code:
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUser u = users[UserName];
MailMessage mail = new MailMessage();
mail.To.Add(u.Email);
mail.From = new MailAddress("me#hotmail.com");
mail.Subject = "Purchase invoice" + newOrder.OrderID;
string bodyText = "";
double unitQtyPrice = 0;
double totalPrice = 0;
foreach (var cItem in cartList)
{
Math.Round(cItem.UnitCost, 2);
bodyText = bodyText + '\n'
+ cItem.ProductID.ToString() + '\t'
+ cItem.ModelName + '\t'
+ cItem.ModelNumber + '\t'
+ cItem.UnitCost.ToString() + '\t'
+ cItem.Quantity.ToString() + '\t';
unitQtyPrice = cItem.Quantity * (double)cItem.UnitCost;
totalPrice += unitQtyPrice;
}
Math.Round(totalPrice, 2);
mail.Body = "Thank you for shopping with us. Your purchase details are as follow:"
+ '\n' + "ProductID:" + '\t' + "ModelName" + '\t' + "ModelNumber" + '\t' + "UnitPrice" + '\t' + "Quantity"
+ '\n' + bodyText + '\n' + '\n' + '\t' + '\t' + "Total Price:" + totalPrice ;
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //ssl must be enabled for hotmail
NetworkCredential credentials = new NetworkCredential("me#hotmail.com", "xxxx");
client.Credentials = credentials;
try
{
client.Send(mail);
}
catch (Exception exp)
{
throw new Exception("ERROR: Fail to send email - " + exp.Message.ToString(), exp);
}

You have it set to HTML, which is whitespace-insensitive. If you want it to be sent as plaintext with line breaks and all, don't set IsBodyHtml.
Alternatively, you can include actual HTML markup to lay out your email, which may be a better solution.

Just write you mail.Body part in an HTML language...
and set
mail.IsBodyHtml = true;

Related

MailKit receive emails doesn't show message.Body

I'm receiving emails OK, except that message.TextBody is showing a blank when there is a message present.
message.HtmlBody shows the body text amongst a whole lot of html stuff, obviously, but I'm looking for message.TextBody.
message.TextBody.ToString() shows an error
Object reference not set to an instance of an object
I'm using the following code:
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
client.Connect("pop.gmail.com", 995, true);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("aaaa#gmail.com", "ssss");
gstrEmailMessages = gstrEmailMessages + client.Count + "\n";
//Fetch emails:
for (int i = 0; i < client.Count; i++)
{
var message = client.GetMessage(i);
gstrEmailMessages = gstrEmailMessages + "Subject: " + message.Subject + "\n";
gstrEmailMessages = gstrEmailMessages + "TextBody: " + message.TextBody + "\n";
gstrEmailMessages = gstrEmailMessages + "HtmlBody: " + message.HtmlBody + "\n";
}
//Disconnect connection:
client.Disconnect(true);
Why does message.TextBody show a blank?
Not all messages will have both an HTML and a plain-text body. In fact, it's possible for some messages to have neither.
In general, though, most messages will have at least 1 of those.

Property or indexer "Attachments" cannot be assigned to -- it is read only

I´m trying to send mail with image attachment, but it still throwing error
(*Property or indexer "Attachments" cannot be assigned to -- it is read only *)
string pathToPic = #"c:\MyDir\Img\img"+ automaticalyGeneratedNumber.toString() + ".png";
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
Attachments = new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"),
})
{
smtp.Send(message);
}
Why complicate the code like that. You need to use message.Attachments.Add since the Attachments property is read-only :
var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
};
message.Attachments.Add(new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"));
using (message)
{
smtp.Send(message);
}

C#.NET send email based on two conditions

I have the following code segment that sends an email to users based on 'RequestApproval' being set to true on their records in a SQL table - it works perfectly.
SmtpClient mySmtpClient = new SmtpClient();
List<SigList> LST_SigList = LK_CRFData.SigLists.Where(x => x.RequestApproval == true).ToList();
string URL = sponsorURL + OB_CRF.id;
foreach (SigList OB_SigList in LST_SigList)
{
string Name = OB_SigList.UserName.Trim();
Name = Name.Substring(0, Name.IndexOf("."));
Name = Name[0].ToString().ToUpper() + Name.Substring(1, Name.Length - 1);
MailMessage myMessage = new MailMessage("SponsorApproved#nhs.net", OB_SigList.EmailAddress);
myMessage.Subject = "Sponsor has approved the request on the " + TB_DateTimeofImplementationStart.Text.Substring(0, 10) + " for \"" + TB_CNNO.Text + " " + TB_Title.Text + "\"";
myMessage.Body = "Dear " + Name + ", \n\nThe sponsor has now approved CN NO : " + TB_CNNO.Text + "\nTitle : " + TB_Title.Text + "\nImplementation Date : " + TB_DateTimeofImplementationStart.Text.Substring(0, 10) + "\n\nClick the link to open the document:\n" + URL;
mySmtpClient.Send(myMessage);
}
However, for certain functions, I want to send the email where 'Request approval is set to True OR False. I've ammended it to the following to no avail:
List<SigList> LST_SigList = LK_CRFData.SigLists.Where(x => x.RequestApproval == true || x.RequestApproval == false).ToList();
It still sends emails out the old way -only to those who have Request Approval' set to true.
Any ideas?
Thanks

\n isn't working in sending emails

I've made a code which sends mail through form. This is my method:
protected void SendMail()
{
string firstName = fName.Text.ToString();
string lastName = lName.Text.ToString();
string event = eventName.Text.ToString();
string phoneNum = phone.Text.ToString();
string pass1 = pass.Text.ToString();
string address1=address.Text.ToString();
string email = gmail.Text.ToString();
string body = "From: " + firstName+" " +lastName+ "\n";
string subject = "title " + event;
body += "Email: " + email + "\n";
body += "Event: " + event + "\n";
body += "Phone Number: " + phoneNum + "\n";
body += "Password: " + pass1 + "\n";
body += "Event address: " + address1 + "\n";
// smtp settings
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add("aaaaa#gmail.com");
mail.From = new MailAddress("aaaaa#gmail.com", "title", System.Text.Encoding.UTF8);
mail.Subject = "title";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = System.Net.Mail.MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("aaaa#gmail.com", "password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(mail);
Response.Redirect("sadasd.aspx");
}
catch (Exception ex)
{
}
}
My Problem is that the email is a big mess and the \n isn't working. How can I get a line down? Why isn't it working?
I this "\n" should be replaced with "<br />". and StringBuilder will be more suitable to build the MailMessage, the code will be like the following:
StringBuilder mailBodyBuilder = new StringBuilder();
mailBodyBuilder.Append("From: " + firstName +" " + lastName + "<br />");
mailBodyBuilder.Append("Email: " + email + "<br />");
mailBodyBuilder.Append("Event: " + event + "<br />");
mailBodyBuilder.Append("Phone Number: " + phoneNum + "<br />");
mailBodyBuilder.Append("Password: " + pass1 + "<br />");
mailBodyBuilder.Append("Event address: " + address1 + "<br />");
// rest of contents here
// send the mail

.Net.Mail body message lose the format while is sent c# .net

I'm using a string builder to create a body message while trying to do something.
the issue es I'm getting the value from the string builder and this one is formatted.
Example from my string builder:
Following files were attached by email:
1. C:\SALASFRI2_20150824094158_ScrubLog.txt - Record Count: 8
2. C:\SALASFRI2_20150824102328_ScrubLog.txt - Record Count: 8
3. C:\SALASFRI2_20150824102516_ScrubLog.txt - Record Count: 8
4. C:\SALASFRI2_20160121125353_ScrubLog.txt - Record Count: 8
5. C:\SALASFRI2_20160121125659_ScrubLog.txt - Record Count: 8
===================================================
Total Files: 5
Please contact your system administrator for any further assitance.
That's exactly how the stringbuilder looks, but when the email arrived, it lose their format as follow:
do you know if there is a property to don't lose the format when it arrive to my email?
This is my code:
if (Notification.IncludeFileName || Notification.IncludeRecordCount)
{
BodyMessage.Append("Following files were attached by email: \n");
for (int index = 0; index < NumberOfFiles; index++)
{
if (Notification.IncludeFileName && Notification.IncludeRecordCount)
BodyMessage.Append((index + 1) + ". " + LocalFiles[index] + " - Record Count: " + File.ReadLines(LocalFiles[index]).Count() + "\n");
else
BodyMessage.Append((index + 1) + ". " + LocalFiles[index] + File.ReadLines(LocalFiles[index]).Count() + "\n");
}
}
if (Notification.IncludeNumberOfFiles)
{
BodyMessage.Append("\n===================================================\n\n");
BodyMessage.Append("Total Files: " + NumberOfFiles + "\n");
}
BodyMessage.Append("\nPlease contact your system administrator for any further assitance.");
////////////////////END OF SUBJECT AND BODY MAIL MESSAGE VALIDATION
////////............SEND THE ATTACHMENTS THROUGH EMAIL................///////////
try
{
MailMessage Email = new MailMessage();
SmtpClient smtp = new SmtpClient(AppConfiguration.SMTPServer);
Email.From = new MailAddress(AppConfiguration.EmailAddress);
Email.To.Add(protocol.SMTPEmailList);
Email.Subject = EmailSubject;
Email.Body = BodyMessage.ToString();
if (directories.Zip)
Email.Attachments.Add(new Attachment(ZipName));
else
foreach (var attachment in LocalFiles)
{
Email.Attachments.Add(new Attachment(attachment));
}
smtp.Port = AppConfiguration.SmtpPort;
smtp.UseDefaultCredentials = true;
smtp.Send(Email);
Email.Dispose();
You probably need to use "\r\n" as your newline sequence instead of just "\n".

Categories