Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem sending email with SmtpClient in C#

Tags:

c#

asp.net-mvc

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("[email protected]");
MailAddress SendTo = new MailAddress("[email protected]");
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?

like image 284
photo_tom Avatar asked Dec 22 '22 08:12

photo_tom


2 Answers

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;
like image 191
ParmesanCodice Avatar answered Feb 15 '23 03:02

ParmesanCodice


Try this change:

plainView.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
like image 37
Keith Adler Avatar answered Feb 15 '23 01:02

Keith Adler