\n isn't working in sending emails - c#

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

Related

Blazor MailKit Email Template

I have a Calculator and i use the following to send the results by email
public void SendEmail()
{
emailbody = "<i>Dear, " + model.FullName;
emailbody = emailbody + "<br>";
emailbody = emailbody + "<br><i>Here are the results using Dromon's Bureau of Shipping EEXI Calulator for: " + model.VesselName + " with IMO Number: </i>" + model.IMONumber;
emailbody = emailbody + "<br><br>";
emailbody = emailbody + "<hr>";
emailbody = emailbody + "<br><b>Full Name: </b>" + model.FullName;
emailbody = emailbody + "<br><b>Email Adsress: </b>" + model.EmailAddress;
emailbody = emailbody + "<br><b>ISM Manager: </b>" + model.ISMManager;
emailbody = emailbody + "<br><b>Vessel Name: </b>" + model.VesselName;
emailbody = emailbody + "<br><b>IMO Number: </b>" + model.IMONumber;
emailbody = emailbody + "<br><b>Type of Vessel: </b>" + model.TypeOfVessel;
emailbody = emailbody + "<br><b>Gross Tonnage: </b>" + model.GrossTonnage;
emailbody = emailbody + "<br><b>Year of built: </b>" + model.YearOfBuilt;
emailbody = emailbody + "<br>";
emailbody = emailbody + "<br><b>Dame and time of Calculation: </b>" + #DateTime.Now;
emailbody = emailbody + "<br><b>EEXI Value: </b>" + eexi;
emailbody = emailbody + "<br><b>Compliance with EEXI regulation: </b>" + Convert.ToString(model.Compliance);
emailbody = emailbody + "<br><br>";
emailbody = emailbody + "<hr>";
emailbody = emailbody + "<br><i>Thank you for using Dromon's Bureau of Shipping EEXI Calculator.";
emailbody = emailbody + "<br><small>This message was sent from an unmonitored address. Please do not respond to this message. Send all inquiries to it#dromon.com";
email.From.Add(MailboxAddress.Parse("******"));
email.To.Add(MailboxAddress.Parse(model.EmailAddress));
email.Bcc.Add(MailboxAddress.Parse("******"));
email.Subject = "Dromon Bureau of Shipping EEXI calculation Results for IMO Number: " + model.IMONumber;
email.Body = new TextPart(TextFormat.Html) { Text = emailbody };
using var smtp = new SmtpClient();
smtp.Connect("mail.******.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("******", "******");
smtp.Send(email);
smtp.Disconnect(true);
}
}
And the result email is:
Now I would like to make the email body an HTML template so it looks more professional and binds the model values similar to what I have now. Please note that I cannot bind values on another page.

cannot send fileupload.postedfile.inputstream as an attachment - ERROR: cannot convert system.io.stream to string

I need to send a pdf as an attachment. I am using a html template as mailbody. My problem is the error displayed while trying to send the attachment as follows.
email.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream), pdffilename);
The FileUpload1.PostedFile.InputStream is the error code.
My full code is displayed below:
private void send_job_notification(string name, string app_email, string job_id, string job_title, string experience,string pdffilename)
{
string to = "aaa#bbb.com";
SmtpClient smtp_server = new SmtpClient();
MailMessage email = new MailMessage("aaa#bbb.com", to);
smtp_server.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp_server.UseDefaultCredentials = false;
smtp_server.Credentials = new System.Net.NetworkCredential("aaa#bbb.com", "PASSWORD");
smtp_server.Port = 25;
smtp_server.EnableSsl = false;
smtp_server.Host = "zzz.bbb.com";
email.From = new MailAddress("aaa#bbb.com");
email.To.Add(to);
email.Subject = "New Job request submitted for company";
email.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream), pdffilename);
email.IsBodyHtml = true;
string FilePath = Server.MapPath("~/emailnewtemplate.html");
StreamReader str = new StreamReader(FilePath);
string MailText = str.ReadToEnd();
str.Close();
string line1 = "<h4>Dear Management</h4>";
string line2 = "<h4>A new job request has been receieved. The applicant details are as follows</h4>";
string table_open = "<table class='table table-responsive-sm'>";
string row_1 = "<tr><td>Name : </td><td> " + name + " </td></tr>";
string row_2 = "<tr><td>Email : </td><td> " + app_email + " </td></tr>";
string row_3 = "<tr><td>Job ID : </td><td> " + job_id + " </td></tr>";
string row_4 = "<tr><td>Job Title : </td><td> " + job_title + " </td></tr>";
string row_5 = "<tr><td>Experience : </td><td> " + experience + " </td></tr>";
string table_close = "</table>";
string line3 = table_open + row_1 + row_2 + row_3 + row_4 + row_5 + table_close;
string htmlbody = line1 + line2 + line3;
MailText = MailText.Replace("[#####HERE#####]", htmlbody);
email.Body = MailText;
smtp_server.Send(email);
}
I think a wrongly placed bracket is your problem, It looks like you tried to use the constructor Attachment(Stream, String) of the Attachment class but you supplied only the stream. the constructor of Attachment class that accepts only one parameter is expecting a string that's what the error message says
correct it as :
email.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, pdffilename));

Send a mail from web server using asp.net? Not working in Godaddy webserver

I have a website, there is a Contact Us tab. User have to fill the form and when click the button I should get a mail from user.
It's working fine when I am running from localhost. But the same code it is not running in Godaddy webserver. This is my code
try
{
MailMessage mailMessage = new MailMessage("From#gmail.com", "To#mydomain.com");
mailMessage.Subject = txtSubject.Text;
string msg = "#Sender Name: " + txtUserName.Text + "#Sender Email ID: " + txtUserEmailId.Text + "#Company Name: " + txtCompanyName.Text + "#Mobile No: " + txtMobileNo.Text + "#Office Telephone No: " + txtOfficeTelephoneNo.Text + "#Office Fax No: " + txtOfficeFaxNo.Text + "#City: " + txtCity.Text + "#Sender Message: " + txtMessage.Text;
string newMsg = msg.Replace("#", "\n");
mailMessage.Body = newMsg;
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "From#gmail.com",
Password = "Password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
catch (Exception ee)
{
Response.Write(ee.Message);
}

send List<> values with Body in mail - SMTP server

I have to send mail through SMTP server. I can able to send it with single values. But, I want to send List<> values as message body in table format or some other structure. I include my code following :
MailMessage mailObj = new MailMessage("abc#gmail.com", "xyz#gmail.com", "Reg : send mail",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com", ***);
SMTPServer.Host = "smtp.gmail.com";
SMTPServer.EnableSsl = true;
SMTPServer.Timeout = 200000;
SMTPServer.Credentials = new System.Net.NetworkCredential("asd#gmail.com", "******");
SMTPServer.Send(mailObj);
I have my list of values as follows :
List<TimesheetValues> mailBody = new SampleDAO().GetDataForMail(dt1, satDate);
How can I include this List<> values with body and send?
I try with following :
List<TimesheetValues> Msg = new List<TimesheetValues>(); string strMsg = ""; int n=1;
foreach(var item in mailBody)
{
strMsg = strMsg + "<table><tr><td>" + n + "</td><td>" + item.Project_Name + "</td><td>" + item.Task_Name + "</td><td>" + item.Notes + "</td><td>" + item.Hrs_Worked + "</td></tr></table>";
n++;
}
strMsg = strMsg + "</br>";
MailMessage mailObj = new MailMessage("abc123#gmail.com", "xyz123#gmail.com", "Reg : Timesheet",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
mailObj.Body = "Emp Name : " + "Emp1" + Environment.NewLine + "Date From : " + Date2 + " Date To : " + Date6 + Environment.NewLine + strMsg;
Now I get all records but i have tr td tags with in records and not display as a table. How can i acheive this ?
can anyone help to overcome this..
Thanks in advance...
If you want to read the string into a list again, serialize is better.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(yourList);
mailObj.Body = json;
You can also deserialize in the other side:
List<string> g = JsonConvert.DeserializeObject<List<string>>(body);
I try with this following :
string strMsg = ""
strMsg = timsheetMail + " <table style=\"border-collapse:collapse; text-align:center;\" border=\"1\"><tr><td> Date </td><td> Working Hours </td><td> Task </td><td>Comments</td></tr>";
List<TimesheetValues> Msg = new List<TimesheetValues>(); int n=1;
foreach(var item in mailBody)
{
timesheetData = new TimesheetDetailModel();
timesheetData.Task_Id = matrix.Task_Id;
timesheetData.Hours = matrix.Hours;
//timesheetData.Date = matrix.Date.Date;
timesheetData.Date = matrix.Date.AddDays(1);
timesheetData.EmpId = Convert.ToInt32(Session["EmpId"].ToString());
timesheetData.Notes = matrix.Notes;
strMsg = strMsg+ " <tr><td> " + timesheetData.Date.ToString("dd/MM/yyyy") + "</td><td>" + timesheetData.Hours + "</td><td>" + task + "</td><td>" + timesheetData.Notes + "</td></tr>";
n++;
}
strMsg = strMsg + "</table>";
Its working good now..

MailMessage smtpClient not working after release

The following code is working fine when debugging with localhost but not after I release to the web-server.
protected void SendMail()
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("xxxxxx#gmail.com");
mailMessage.To.Add("xxxxxx#gmail.com");
mailMessage.Subject = ddlSubject.Text;
mailMessage.Body = "<b>Sender Title: </b> " + ddlTitle.SelectedItem.Text + "<br/>"
+ "<b>Sender First Name: </b> " + txtFName.Text + "<br/>"
+ "<b>Sender Last Name: </b> " + txtLName.Text + "<br/>"
+ "<b>Sender Email: </b> " + txtEmail.Text + "<br/>"
+ "<b>Sender Phone: </b> " + txtPhone.Text + "<br/>"
+ "<b>Sender Address: </b> " + txtAddress.Text + "<br/>"
+ "<b>Sender Suburb: </b> " + ddlSuburbs.SelectedItem.Text + "<br/>"
+ "<b>Sender Message: </b> " + contactMessage.InnerText + "<br/>";
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential("xxxxxxx#gmail.com", "xxxxxx");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
lblConfirmation.Text = "Thank you " + ddlTitle.SelectedItem.Text + " " + txtFName.Text.ToUpper() + " " + txtLName.Text.ToUpper() + " for contacting us. We will try to get back to you ASAP";
}
NOTE The website is using SSL.
Make sure port=25.
try
{
MailMessage msg = new MailMessage ();
MailAddress fromAdd = new MailAddress("fromemail#email.com");
msg.[To].Add("toemail#email.com");
msg.Subject = "Choose Session Members";
msg.From = fromAdd;
msg .IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
msg .BodyEncoding = Encoding.Default;
msg.Body = "<center><table><tr><td><h1>Your Message</h1><br/><br/></td></tr>";
msg.Body = msg.Body + "</table></center>";
SmtpClient smtpClient = new SmtpClient ("smtp.yourserver.com", "25");
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("yourname#yourserver.com", "password");
smtpClient .DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(msg);
smtpClient.Dispose();
}
catch (exception ex){
Label1.Text = ex.ToString();
}

Categories