I am Sending Mail to Specific User, in mail.body after my message I wanted to Add Few more details which will be in new line, I tried br,n, Environment.NewLine but nothing seems to be working, is there a way which I can try.
Thank you In Advance.
protected void SendMail()
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("xyz");
mail.To.Add("abc");
mail.Subject = "INCOMPLETE APPLICATION CASE ID [CASE ID]";
mail.IsBodyHtml = true;
mail.Body = "Your Incomplete Grade Application has been Result[]";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(Server.MapPath("files/CS00022904.pdf"));
mail.Attachments.Add(attachment);
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "10.12.46.3";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("", "");
}
smtp.Send(mail);
}
You should be able to use br:
mail.Body = "Your Incomplete Grade Application has been Result[] <br /> Here is another line of text!";
There are few ways, one of these:
var sb = new StringBuilder();
sb.Append("Line 1").Append("<br />");
. . . . .
sb.Append("Line N").Append("<br />");
// Sometimes later
mail.Body = sb.ToString();
Advantage of string builder is that you can efficiently add lines in loop and in differed way. you can pass it to different methods and keep adding lines, and use it in the end. This is also helpful if your text stored as lines and you can iterated them.
Since the BodyFormat is set to HTML, you can just add <br /> to the body string.
Related
I am sending emails thorugh c#. The body of the mail is dynamic i.e. user fills it in before sending the mail. Issue is the body text is coming in a single line instead of multiple lines as they should.
using (MailMessage mm = new MailMessage(txtEmail.Text.Trim(), email.Trim()))
{
try
{
mm.CC.Add(txtcc.Text.Trim());
mm.Subject = txtSubject.Text.Trim();
mm.Body = txtBody.Text;
MemoryStream pdf = new MemoryStream(bytes);
mm.Attachments.Add(new Attachment(pdf, "Report.pdf"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = txtEmail.Text.Trim();
credentials.Password = txtPassword.Text.Trim();
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
catch (Exception ex)
{
Alert.show1("Could not send the e-mail - error: " + ex.Message, this);
return;
}
}
If you dont need the potential of HTML formatting, you could avoid the problem changing the email format to plain text. This could also avoid user entering text that could be parsed as html.
mm.IsBodyHtml = false;
Otherwise you should change the end line character to html breaking line:
mm.IsBodyHtml = true;
mm.Body = mm.Body.Replace(#"\n", "<br />");
In case of the html format option, It would be wise to follow Fildor's comment and add an alternateView in plain text for email clients that are not html capable.
I have a variable name that holds a hyperlink; I would like to send the hyperlink within an email.
I can send the email ok, but the hyperlink appears as text i.e.[http://www.google.com]Click here
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"], "FileTransfer");
mailMessage.Subject = "FileTransfer";
var body = new StringBuilder();
body.AppendFormat("<html><head></head><body> Hello World" + "<br />" + "<a href='{0}'>Click here</a></body></html>", link);
mailMessage.IsBodyHtml = true;
mailMessage.Body = body.ToString();
mailMessage.To.Add(new MailAddress(toEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
Try replacing this...
body.AppendFormat("<html><head></head><body> Hello World" + "<br />" + "<a href='{0}'>Click here</a></body></html>", link);
with this
body.Append("<html><head></head><body> Hello World" + "<br />" + "Click here</body></html>");
According to https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx
It seems like you have to set the content type and create an alternate view. Or if you don't want to have a plaintext version, set the default view to text/html
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
recipients,
"This e-mail message has multiple views.",
"This is some plain text.");
// Construct the alternate body as HTML.
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
body += "</FONT></DIV></BODY></HTML>";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
Some email provider software won't be capable of displaying text/html. Whether this is a protective measure or just lack of support, I believe this would be the best solution since it compensates for both cases.
I developing an app which is an email generator, the thing is that I need to send a carbon copy of my email to the same email I am using to send the original one, basically I need to duplicate every email. But when I set the cc email the code simply ignores the CC.
C# Code:
const string fromPassword = "password";
string subject = "Subject " + sXmlArray[0].ToString();
SmtpClient smtp = new SmtpClient();
//Google SMTP Host
smtp.Host = "smtp.gmail.com";
//smtp.Host = "smtp.office365.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("myEmail#domain.com", fromPassword);
smtp.Timeout = 100000;
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = StrContent.ToString();
//Carbon Copy
//HERE IS THE ISSUE
MailAddress CarbonCopy = new MailAddress("myEmail#domain.com");
message.CC.Add(CarbonCopy);
smtp.Send(message);
Why the code ignores this piece of code? If I declare a different email it works fine?
Can somebody help me out with this issue? Thanks in advance.
This question already has answers here:
How to embed multiple images in email body using .NET
(7 answers)
Closed 9 years ago.
i trying to send test email from my local dev machine, with an image. the image is not being sent as an attachment.
May be its a stupid question but is there any way i can send email from my website running on my local machine for test purposes before i host it on www.
public static void SendMail(string emailBody, string to, string from, string subject)
{
MailMessage mailMessage = new MailMessage("to#to.com", "from#test.com");
mailMessage.Subject = subject;
mailMessage.Body = emailBody;
mailMessage.IsBodyHtml = true;
//mailMessage.Body += "<br /><br /> <asp:Image ID='Image1' runat='server' ImageUrl='~/images/banner.jpg' />";
string path = System.Web.HttpContext.Current.Server.MapPath(#"~/images/banner.jpg");
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><br/><img src=cid:companylogo/><br></body></html>" + emailBody, null, MediaTypeNames.Text.Html);LinkedResource logo = new LinkedResource(path);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand sc = new SqlCommand("SELECT EmailAdd FROM Volunteers where Country like 'United K%' and Race like 'Pak%' ", con);
con.Open();
SqlDataReader reader = sc.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
mailMessage.To.Add(reader[0].ToString());
}
}
reader.Close();
}
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
}
It looks as though you may not be setting the correct CID of the image. This is the method I'm using in one of my applications:
// Construct the MailMessage object to be relayed to the SMTP server
message = new MailMessage("to#to.com", "from#test.com");
string path = System.Web.HttpContext.Current.Server.MapPath(#"~/images/banner.jpg");
byte[] image = LoadImageAsByteArray(path);
// create a stream object from the file contents
var stream = new MemoryStream(image);
// create a mailAttachment object
var mailAttachment = new System.Net.Mail.Attachment(stream, "bannerAttachment.jpg")
{
// set the content id of the attachment so our email src links are valid
ContentId = Guid.NewGuid().ToString("N")
};
// set the attachment inline so it does not appear in the mail client as an attachment
mailAttachment.ContentDisposition.Inline = true;
// and then add the newly created mailAttachment object to the Attachments collection
message.Attachments.Add(mailAttachment);
And...one thing I found "strange" is your use of AlternateView - it seems a bit redundant. I'd advise creating the body like so:
// Construct the body
var body = string.Format("<html><body><br/><img src=cid:{0} /><br />{1}</body></html>", mailAttachment.ContentId, emailBody);
// Subject
message.Subject = "Whatever"
// Ensure this is set to true so images are embedded correctly
message.IsBodyHtml = true;
// finally, add the body
message.Body = body;
// Create an smtp client object to initiate a connection with the server
var client = new SmtpClient(smtpServerAddress, smtpServerPort.Value);
// tell the client that we will be sending via the network (as opposed to using a pickup directory)
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// and finally send the message
client.Send(message);
);
NOTE: You'll have to take care of your own authentication etc. as I have not included that. Also, this is an excerpt of my own production code, so please, let me know how you go. I'll be more than happy to modify my answer accordingly.
here is your solution.
string ss = "<div style='background:#e0e1e3;width:800px; margin:20px auto;border:1px solid #d8d9db;'>";
ss = ss + "<div style='background:#ffffff; padding:10px;'>";
ss = ss + "<img src='http://example.com/images/myimage.jpg' /></div>";
MailMessage MailMsg = new MailMessage();
MailMsg.To.Add("test#test.com");
MailMsg.From = new MailAddress("Test.co.in");
MailMsg.Subject = "Your subject";
MailMsg.BodyEncoding = System.Text.Encoding.UTF8;
MailMsg.IsBodyHtml = true;
MailMsg.Priority = MailPriority.High;
MailMsg.Body = ss;
SmtpClient tempsmtp = new SmtpClient();
tempsmtp.Host = "smtp.gmail.com";
tempsmtp.Port = 587;
tempsmtp.EnableSsl = true;
tempsmtp.Credentials = new System.Net.NetworkCredential("test#test.com", "welcome");
tempsmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
tempsmtp.Send(MailMsg);
MailMessage message = new MailMessage();
message.From = new MailAddress("hkar#gmail.com");
message.Subject = "Subject";
message.Body = "Please login";
SmtpClient smtp = new SmtpClient();
message.To.Add("karaman#gmail.com");
smtp.Send(message);
I want to have a hyperlink in the body of sent mail where it says "login". How can I do that?
message.Body = "Please login";
Make sure you highlight when sending that the content is HTML though.
message.IsBodyHTML = true;
Set the message to message.IsBodyHTML = true
Login
message.Body = string.Format("Click <a href='{0}'>here</a> to login", loginUrl);
Format the message as HTML and make sure to set the IsBodyHtml property on the MailMessage to true:
message.IsBodyHtml = true;
System.Text.StringBuildersb = new System.Text.StringBuilder();
System.Web.Mail.MailMessage mail = new System.Mail.Web.MailMessage();
mail.To = "recipient#address";
mail.From = "sender";
mail.Subject = "Test";
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
sb.Append("<html><head><title>Test</title><body>"); //HTML content which you want to send
mail.Body = sb.ToString();
System.Web.Mail.SmtpMail.SmtpServer = "localhost"; //Your Smtp Server
System.Web.Mail.SmtpMail.Send(mail);
You just have to set the format of body to html then you can add html element within the bosy of mail message