Problem sending email with SmtpClient in C# - c#

I have an ASP.Net/MVC application and I'm trying to send HTML emails. I'm doing this by reading in an HTML file with tokens, then replacing the tokens. That part is fine and generates HTML that is exactly what I want, but when I send the email, what I'm receiving looks like -
<style type=3D"text/css">=
=0D=0A.styleTitles=0D=0A{=0D=0Afont-weight:=bold;=0D=0A}=0D=0A
.style1=0D=0A {=0D=0A
and should look like
<style type="text/css">
.styleTitles
{
font-weight: bold;
}
.style1
{
height: 15px;
}
I've looked on the web and I can't seem to find the correct syntax to send the message. I've seen some solutions, but none seem to work.
My current test code is -
SmtpClient smtpclient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress SendFrom = new MailAddress("xxxx#abc.com");
MailAddress SendTo = new MailAddress("zzzz#gmail.com");
MailMessage MyMessage = new MailMessage(SendFrom, SendTo);
var plainView = AlternateView.CreateAlternateViewFromString(msgBody,null,"text/html");
plainView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
MyMessage.AlternateViews.Add(plainView);
MyMessage.IsBodyHtml = true;
MyMessage.Subject = subjectLine;
MyMessage.Body = msgBody;
smtpclient.Send(MyMessage);
Any Suggestions?

Maybe something like this:
var plainView = AlternateView.CreateAlternateViewFromString(msgBody, new ContentType("text/plain; charset=UTF-8"));
MyMessage.AlternateViews.Add(plainView);
MyMessage.BodyEncoding = Encoding.UTF8;
MyMessage.IsBodyHtml = true;
MyMessage.Subject = subjectLine;
MyMessage.Body = msgBody;

Try this change:
plainView.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

To set the transfer encoding to 8bit, taken from here , you have to :
message.Body = null;
using (AlternateView body =
AlternateView.CreateAlternateViewFromString(
"Some Message Body",
message.BodyEncoding,
message.IsBodyHtml ? "text/html" : null))
{
body.TransferEncoding =
TransferEncoding.SevenBit;
message.AlternateViews.Add(body);
}

This might not be the answer you need, but have you considered using XSLT for the translation of your email messages? I'm busy with a project that sends emails, and its pretty nice to use XSLT as part of the solution. Also means in future the template can easily be customized in an industry standardized way, maybe you should consider making the change?

It's strange, but more simple code is work for me:
var message = new MailMessage(Email, mailTo);
message.IsBodyHtml = true;
message.SubjectEncoding = message.BodyEncoding = Encoding.UTF8;
message.Subject = "Subject";
message.Body = msgBody;
smtpclient.Send(message);

string emailMessage="a skjdhak kdkand";
MailMessage mail = new MailMessage();
mail.To.Add(obj_Artist.EmailAddress);
mail.From = new MailAddress(EmailList[0].FromEmail, "Sentric Music - Rights Management");
mail.Subject = (EmailList[0].Subject);
if (EmailList[0].BCC1 != null && EmailList[0].BCC1 != string.Empty)
{
mail.Bcc.Add(EmailList[0].BCC1);
}
if (EmailList[0].BCC2 != null && EmailList[0].BCC2 != string.Empty)
{
mail.Bcc.Add(EmailList[0].BCC2);
}
if (EmailList[0].CC1 != null && EmailList[0].CC1 != string.Empty)
{
mail.CC.Add(EmailList[0].CC1);
}
if (EmailList[0].CC2 != null && EmailList[0].CC2 != string.Empty)
{
mail.CC.Add(EmailList[0].CC2);`enter code here`
}
string Body = emailMessage;
mail.Body = Body;
mail.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
mail.IsBodyHtml = true;
AlternateView plainView = AlternateView.CreateAlternateViewFromString
(System.Text.RegularExpressions.Regex.Replace(Body, #"<(.|\n)*?>", string.Empty), null, "text/plain");
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(mail);

Related

Send e-mail with image on body

I want to send an e-mail with a logo at the top of the body. This is my method:
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
The method is sending the e-mail, but the image is being sent as an attachment. I've tried to do this:
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"), MediaTypeNames.Image.Jpeg);
But when I add "MediaTypeNames.Image.Jpeg" in this line, the e-mail is sent without the image at all.
Someone can help me on this? Thanks in advance!
You could convert your image to base64 and add that in src or you could just give the page where is the image is located.
You could try the library MailKit. Sending embedded images works well with this library.
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
stream.Position = 0;
var resource = builder.LinkedResources.Add(contentId, stream);
resource.ContentId = contentId;
// in the email message, there is img with src="cid:contentId"
Another example of embedding images is here.
You can use it :
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = 0; //add port here
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
//add file here
Attachment attachment = new Attachment("c://image");
attachment.ContentDisposition.Inline = true;
message.Attachments.Add(attachment);
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}

email body coming in a single line

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.

Unable to decode danish characters for email

I have some code to send an email. data for email is coming from third party API, which will look like this å equivalent of it is danish character å. but email shows s å .
Is there any way i can transform this one in to correct?
My code to send mail is like this
SmtpClient client = new SmtpClient();
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
foreach (string toEmail in toEmails.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
mail.To.Add(toEmail.Trim());
mail.Subject = subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = isHtml;
mail.Priority = MailPriority.Normal;
if (attachments != null)
{
foreach (string key in attachments.Keys)
{
Attachment mailAttachment = new Attachment(attachments[key], key);
mail.Attachments.Add(mailAttachment);
}
}
client.Send(mail);
retValue = true;
Note: Fixed the issue by using L.B's answer . but i am still having some issues like
this. in my email body
Use HttpUtility or WebUtility class
var str = HttpUtility.HtmlDecode("å");
var str = WebUtility.HtmlDecode("å");

SmtpClient sending raw Html

Could anyone tell me why the following code is sending out emails in raw Html? As in, the email looks like when you view a page source.
I have cut down the code so as not to include attachments and from addresses.
If I disable the line with the alternate view the email renders correctly but I also want to send out a plain text version.
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.IsBodyHtml = true;
message.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
message.To.Add(toList);
message.Subject = subject;
message.Body = htmlTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(textTemplate, new ContentType("text/plain")));
client.Send(message);
}
}
Edit: The message was originally sending text as the main body and html as the alternative view but I have run into a problem with accented and foreign characters as described here and wanted to set IsBodyHtml to true, which forces me to set html to the main view.
I had problems with this also but here's a very much cutdown version of code that worked for me...
private MailMessage CreateEmailMessage(string emailAddress) {
MailMessage msg = new MailMessage();
msg.From = new MailAddress(FromEmailAddress, FromName);
msg.To.Add(new MailAddress(emailAddress));
msg.Subject = "Msg Subject here";
string textBody = File.ReadAllText(TextTemplateFile);
string htmlBody = "";
if (EmailFormat == "html") {
htmlBody = File.ReadAllText(HtmlTemplateFile);
foreach (Attachment inline in InlineAttachments) {
inline.ContentDisposition.Inline = true;
msg.Attachments.Add(inline);
}
AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(htmlBody,
new ContentType("text/html"));
msg.AlternateViews.Add(alternateHtml);
AlternateView alternateText = AlternateView.CreateAlternateViewFromString(textBody,
new ContentType("text/plain"));
msg.AlternateViews.Add(alternateText);
}
else {
msg.Body = textBody;
}
return msg;
}
In the end I realised that the 'htmlTemplate' string being passed into the method was defining charset=ISO-8859-1 in the head of the email and therefore overriding any changes I was making in the code.
I changed the charset to UTF-8, and restored my code to this:
using (SmtpClient client = GetSmtpClient(settings)) {
using (MailMessage message = new MailMessage()) {
message.To.Add(toList);
message.Subject = subject;
message.Body = textTemplate;
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType("text/html")));
client.Send(message);
}
}
and can now send both text and html templates as well as cover the accented characters problem.

Send HTML email via C# with SmtpClient

How do I send an HTML email? I use the code in this answer to send emails with SmtpClient, but they're always plain text, so the link in the example message below is not formatted as such.
<p>Welcome to SiteName. To activate your account, visit this URL:
http://SiteName.com/a?key=1234.
</p>
How do I enable HTML in the e-mail messages I send?
This is what I do:
MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
Note that I set the mail message html to true: mail.IsBodyHtml = true;
I believe it was something like:
mailObject.IsBodyHtml = true;
IsBodyHtml = true is undoubtedly the most important part.
But if you want to provide an email with both a text/plain part and a text/html part composed as alternates, it is also possible using the AlternateView class:
MailMessage msg = new MailMessage();
AlternateView plainView = AlternateView
.CreateAlternateViewFromString("Some plaintext", Encoding.UTF8, "text/plain");
// We have something to show in real old mail clients.
msg.AlternateViews.Add(plainView);
string htmlText = "The <b>fancy</b> part.";
AlternateView htmlView =
AlternateView.CreateAlternateViewFromString(htmlText, Encoding.UTF8, "text/html");
msg.AlternateViews.Add(htmlView); // And a html attachment to make sure.
msg.Body = htmlText; // But the basis is the html body
msg.IsBodyHtml = true; // But the basis is the html body
Apply the correct encoding of the Mailbody.
mail.IsBodyHtml = true;
i have an idea , you can add a check box to your project for sending email as html as an option for user , and add this code to enable it :
MailMessage mail = new MailMessage(from, to, subject, message);
if(checkBox1.CheckState == CheckState.Checked )
{
mail.IsBodyHtml = true;
}
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);
If you are using Mailkit,We can use TextBody,HtmlBody and Both for message body. Just write this code. It will help you
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender#address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender#address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = "Hello There";
mailMessage.Body = builder.ToMessageBody();
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user#name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Categories