I have a C# Winforms application I'm working on in Visual Studio 2010, the page in question is a bug reporting form - I have all the details set, email sends fine etc. My issue is attaching a screenshot to the email in the body, I have code set up to allow users to find and select a screenshot they take and attach to the form, but in the body itself it just gives me the text "System.Windows.Forms.Picturebox", or various similarities to that if I try .image.
I've had a look around via Google and here, but can only find topics that are to do with embedding the image or attaching it (and thus require to enter in a specific folder/image etc), whereas my users will be attaching their own image and name from different places. Is there anyway to get the image to be picked up without having to hardcode a location and name that my users will have to follow each time?
Code below:
private void btnBugEmail_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
try
{
SmtpClient client = new SmtpClient("details here");
MailMessage message = new MailMessage();
message.From = new MailAddress("email here");
string mailBox = txtBugAdd.Text.Trim();
message.To.Add(mailBox);
string mailFrom = txtEmailFromBug.Text.Trim();
message.CC.Add(mailFrom);
string mailCC = txtMailCCBug.Text.Trim();
message.Bcc.Add(mailCC);
message.IsBodyHtml = true;
message.Body = "Bug Report - please see below: " +
"\n" + "<br>" + "<b>" + "1. What were you doing at the time of the error?" + "</b>" +
"\n" + "<br>" + rtbTimeOfError.Text +
"\n" + "<br>" + "<b>" + "2. Are you able to repeat the steps and achieve the same error?" + "</b>" +
"\n" + "<br>" + rtbCanRepeat.Text +
"\n" + "<br>" + "<b>" + "3. Does this problem happen again if you change any of the details you have entered?" + "</b>" +
"\n" + "<br>" + rtbChangeDetails.Text;
message.Subject = "Bug Report";
var image = pboxBugImage.Image;
using(var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
message.Attachments.Add(new Attachment(ms, "Screenshot.jpg"));
client.Credentials = new System.Net.NetworkCredential("credentials here");
client.Port = System.Convert.ToInt32(25);
client.Send(message);
}
new Endpage().Show();
this.Close();
}
catch
{
MessageBox.Show("my comment here");
}
}
Take a look to the following link
system.net.mail.mailmessage.attachments
You cannot put a winforms control inside the mailmessage :) it is outputted with ToString()... that is what you see in mail
Example
private void btnBugEmail_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
try
{
SmtpClient client = new SmtpClient("details here");
MailMessage message = new MailMessage();
message.From = new MailAddress("email here");
string mailBox = txtBugAdd.Text.Trim();
message.To.Add(mailBox);
string mailFrom = txtEmailFromBug.Text.Trim();
message.CC.Add(mailFrom);
string mailCC = txtMailCCBug.Text.Trim();
message.Bcc.Add(mailCC);
message.IsBodyHtml = true;
message.Body = "Bug Report - please see below: " +
"\n" + "<br>" + "<b>" + "1. What were you doing at the time of the error?" + "</b>" +
"\n" + "<br>" + rtbTimeOfError.Text +
"\n" + "<br>" + "<b>" + "2. Are you able to repeat the steps and achieve the same error?" + "</b>" +
"\n" + "<br>" + rtbCanRepeat.Text +
"\n" + "<br>" + "<b>" + "3. Does this problem happen again if you change any of the details you have entered?" + "</b>" +
"\n" + "<br>" + rtbChangeDetails.Text;
message.Subject = "Bug Report";
var image = pboxBugImage.Image;
using(var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
message.Attachments.Add(new Attachment(ms, "Screenshot.jpg"));
client.Credentials = new System.Net.NetworkCredential("credentials here");
client.Port = System.Convert.ToInt32(25);
client.Send(message);
}
new Endpage().Show();
this.Close();
}
catch
{
MessageBox.Show("my comment here");
}
}
Take a look at your resources and dispose the memorystream. I didnt for the example, because i wrote it here in editor
Related
I have a support ticket web application, very old, done in ASP.NET webforms
Until 5 October 2021 it has worked perfectly, then has started to miss, sometimes to send out emails.
In the last few days has started to miss sending out most of the emails.
I'm using office365.com as SMTP and POP3 server. POP3 has never given any issue.
I'm using the same account for sending and for reading.
The workload is very very low: I read the POP3 every 5 minutes, and I send out emails just to confirm we have taken in charge the request. And we are talking about 1 email every 1~2 hrs, therefore is not a heavy workload.
This is the code:
private static string sSMTP = "smtp.office365.com";
private static string sPOP3 = "outlook.office365.com";
private static string sEmailAddress = "sender-email#domain.com";
private static string sEmailAccount = "sender-email#domain.com";
private static string sEmailName = "ACME";
private static string sPassword = "SomePassword";
SendMailConfirm("test.user1#gmail.com", "this is a test", "" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), 1);
SendMailConfirm("test.user2#some-domain.com", "this is a test", "" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), 1);
SendMailConfirm("test.user2#another-domain.com", "this is a test", "" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), 1);
private void SendMailConfirm(string sTo, string sSubj, string sBody, int iCallID)
{
SmtpClient client = new SmtpClient(sSMTP);
//authentication
client.Credentials = new System.Net.NetworkCredential(sEmailAccount, sPassword);
client.EnableSsl = true;
client.Port = 587; //tried also 25 with same result.
MailAddress from = new MailAddress(sEmailAddress, sEmailName);
MailAddress to = new MailAddress(sTo);
MailMessage message = new MailMessage(from, to);
message.Subject = sSubj;
message.ReplyTo = new MailAddress("no-reply#domain.com");
message.Body = "Dear user your support ticket has been inserted.\r\n " +
"Request ID: " + iCallID.ToString() + ".\r\n\r\n-----------------\r\n" + sBody;
SendMessage(client, message);
}
private void SendMessage(SmtpClient client, MailMessage message)
{ // here I've tried to add some delay and see what happen but I always get randomly, 90% of the time "Failure sending mail" as exception.
try
{
client.Send(message);
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 1st message to " + message.To + " succesfully sent!!!!!!!!!!!!!! ";
}
catch (Exception ex)
{
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 1st message to " + message.To + " " + ex.Message + "<hr/>"+ex.StackTrace+"<hr/>";
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " -> retry in 1500ms.";
try
{
Thread.Sleep(1500);
client.Send(message);
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 2nd message to " + message.To + " succesfully sent!!!!!!!!!! ";
}
catch (Exception ex2)
{
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 2nd message to " + message.To + " " + ex2.Message;
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " ---> retry in 3000ms.";
try
{
Thread.Sleep(3000);
client.Send(message);
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 3rd message to " + message.To + " succesfully sent!!!! ";
}
catch (Exception ex3)
{
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 3rd message to " + message.To + " " + ex3.Message;
}
}
}
message.Dispose();
}
The same code works perfectly fine using another email provider, but not on SendGrid or Gmail.
Which could be the cause?
Is there any way to get a more talking message error from SMTP?
After several tries, I've found that the issue is in the System.Net.Mail object of the .Net framework.
I've also found that Microsoft strongly suggest to not use it!:
https://learn.microsoft.com/en-gb/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.8
We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn't be used on GitHub.
After testing it also with SendGrid I've obtained the same behaviour.
Therefore the only solution is to move to MailKit
I've made the code changes, to send the message out with MailKit, and after hundreds of tries, it has never failed.
I'm having the oddest issue that I can't even rationalize.
I have a form with several textboxes, one of which is the comments box:
MVC:
<div class="contactUsTextArea">
Comments or Questions:<br />
#Html.TextAreaFor(x => x.Comments, new { maxlength = 990 } )
</div>
Rendered HTML:
<div class="contactUsTextArea">
Comments or Questions:
<br>
<textarea id="Comments" rows="2" name="Comments" maxlength="990" cols="20"></textarea>
</div>
When the forms is submitted, this code runs:
public bool SendEmail(ContactUsModel formSubmission) {
MailMessage email = new MailMessage();
SmtpClient smtp = new SmtpClient();
string upc = formSubmission.ProductUpcCode;
string comments = formSubmission.Comments;
string comments_small = formSubmission.Comments;
if (!string.IsNullOrEmpty(formSubmission.ProductUpcCode) && upc.Length > 14 )
upc = upc.Substring(0, 13);
if (!string.IsNullOrEmpty(comments) && comments.Length > 990)
comments = comments.Substring(0, 989);
if (!string.IsNullOrEmpty(comments_small) && comments_small.Length > 255)
comments_small = comments_small.Substring(0, 254);
string bodyText = "FIRST_NAME:" + formSubmission.FirstName + "\n" +
"LAST_NAME:" + formSubmission.LastName + "\n" +
"COMPANY:" + formSubmission.CompanyName + "\n" +
"ADDRESS:" + formSubmission.StreetAddress + "\n" +
"CITY_TOWN:" + formSubmission.City + "\n" +
"STATE_PROVINCE:" + formSubmission.Province + "\n" +
"ZIP_POSTAL:" + formSubmission.PostalCode + "\n" +
"COUNTRY:CAN\n" +
"EMAIL:" + formSubmission.Email + "\n" +
"PHONE:" + formSubmission.PhoneNumber + "\n" +
"UPC:" + upc + "\n" +
"DATE_CODE:\n" +
"BRAND_PRODUCT:" + formSubmission.ProductName + "\n" +
"COMMENTS:" + comments_small + "\n" +
"FULL_COMMENTS:" + comments + "\n" +
"LANGUAGE:English" + "\n" +
"OPTIN:N";
email.From = new MailAddress(ConfigurationManager.AppSettings["emailSubmission_FROM"]);
email.To.Add(new MailAddress(ConfigurationManager.AppSettings["emailSubmission_TO"]));
email.Subject = ConfigurationManager.AppSettings["emailSubmission_SUBJECT"];
email.IsBodyHtml = false;
email.Body = bodyText;
email.BodyEncoding = System.Text.Encoding.UTF8;
smtp.Send(email);
return true;
}
(Don't ask me why I need a small comments and large comments, clients will be clients)
Anyway, my issue is when I type a comment into the comment box I get this return:
http://i.imgur.com/zraNy.png
However when I copy paste text I get this return:
http://i.imgur.com/doWrw.png
Why is this happening?
There are only a few things that this could be (that I could think of) - both of which are related to the client.
Something with the email client where its not rendering the \n like it should.
Although for Windows, \r\n is the standard, and many applications dont honor '\n' properly. I would try using that for newlines instead of just \n.
Also something with the client, related to encoding (but i doubt it)
Alright... so I'll just post a picture of what my issue was... and then I'm going to go hide in shame in a cave forever.
http://i.imgur.com/tEiKj.png
Thanks for the help though everyone.
Hi I believe I am pretty close to figuring out what is wrong with my code, but was hoping someone could help me out or point me in the right direction. I am able to run my program and on the page where the user is going to be uploading a file it gives me the option to choose a file. But when I press submit other information gets sent to me but the file never comes. I think this is because I am having trouble figuring out where to temporarily save the file when it send to my email. Here is my code at the moment:
Also what this code is for is a comment / request page on my website where the user can comment and also add a screen shot.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
My question is where am I going wrong where in this code do I put where I want the file to be saved.
The below part of the code is what I am using to format the email when it is sent. And pick what will be sent in the email.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
File1.f + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
For some reason now nothing is sending in my emails when I press submit. Also I was trying to figure out how to put in the email the time and date the email was sent. Even though obviously my email will have this information, incase the email is delayed for some reason I would like to have the time and date the user pressed the submit button. Where is says File.F in this part of the code this is where i was trying to figure out how to get the file attachment to go to the email, but I'm not sure what syntax should go there in the code.
It looks like you are trying to attach some file from the user's computer to the email you are sending. If that is the case, you need to upload your file first before you call SendMessage.
In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you.
After you upload your file, pass strSavedLocation, which is the file location you saved the file, to your SendMessage() method.
In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage. strAttachment is the path name to your uploaded file:
var attachment = new Attachment(strAttachment);
// Add time stamp information for the file.
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(strAttachment);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(strAttachment);
disposition.ReadDate = System.IO.File.GetLastAccessTime(strAttachment);
mailMsg.Attachments.Add(attachment);
It looks to me like you have the major parts here minus the handy, System.Net.Mail.Attachment.
If I were doing this, I'd move the file upload handling code into the Submit_Click handler, and then just add the Mail.Attachment code.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
System.Net.Mail.MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
/*** Added mail attachment handling ***/
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strAttachment);
mailMsg.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
}
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
/*** Moved from SendMessage function ****/
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
strSaveLocation + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, strSaveLocation, "");
}
catch
{
}
}
As for the note about using StringBuilder, I agree, and I would use it like this:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat("Bug Name: {0}<br/>", txtBugName.Text.Trim());
sb.AppendFormat("Module Name: {0}<br/>", ddlModule.SelectedValue);
Edited To Add:
Also, see Brad's answer above about using ContentDisposition.
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/
i had a problem in format in email. I want to have a new line..
here's the format in email..
Name: sdds Phone: 343434 Fax: 3434 Email: valencia_arman#yahoo.com Address: dsds Remarks: dsds Giftwrap: Yes Giftwrap Instructions: sdds Details: PEOPLE OF THE BIBLE(SCPOTB-8101-05) 1 x Php 275.00 = Php 275.00 Total: Php275.00
here's my C# code..
mail.Body = "Name: " + newInfo.ContactPerson + Environment.NewLine
+ "Phone: " + newInfo.Phone + Environment.NewLine
+ "Fax: " + newInfo.Fax + Environment.NewLine
+ "Email: " + newInfo.Email + Environment.NewLine
+ "Address: " + newInfo.Address + Environment.NewLine
+ "Remarks: " + newInfo.Notes + Environment.NewLine
+ "Giftwrap: " + rbGiftWrap.SelectedValue + Environment.NewLine
+ "Giftwrap Instructions: " + newInfo.Instructions + Environment.NewLine + Environment.NewLine
+ "Details: " + Environment.NewLine
+ mailDetails;
If you're sending it in HTML, make sure you set the format.
mail.BodyFormat = MailFormat.Html;
And then you can use <br/> should you want to.
UPDATE:
Try this as an alternative:
using System.Net.Mail;
...
MailMessage myMail;
myMail = new MailMessage();
myMail.IsBodyHtml = true;
maybe you can try this...
We create seperate email templates (e.g. EmailTemplate.htm), it includes the message to be sent. You will have no problems for new line in message.
Then this is our Code behind:
private void SendEmail()
{
string emailPath = "../EmailTemplate.htm"; //Define your template path here
string emailBody = string.Empty;
StreamReader sr = new StreamReader(emailPath);
emailBody = sr.ReadToEnd();
sr.Close();
sr.Dispose();
//Send Email; you can refactor this out
MailMessage message = new MailMessage();
MailAddress address = new MailAddress("sender#domain.com", "display name");
message.From = address;
message.To.Add("to#domain.com");
message.Subject = "Your Subject";
message.IsBodyHtml = true; //defines that your email is in Html form
message.Body = emailBody;
//smtp is defined in web.config
SmtpClient smtp = new SmtpClient();
try
{
smtp.Send(message);
}
catch (Exception ex)
{
//catch errors here...
}
}
Did you try "+\n" instead of Environment.NewLine?