简体   繁体   中英

Set Content-Transfer-Encoding to Quoted-printable with .NET MailMessage

When i send mails with .NET SmtpClient, i have noticed the content transfer encoding is set to base64 when i check the source code of the mail.

I need to set it to Quoted-printable. How can i achieve this ? Thanks in advance

public virtual MailMessage GetMailMessage(string body, string from, string [] user_emails, string [] back_office_emails, string subject)
{             
    MailMessage message = new MailMessage();
    message.IsBodyHtml = true;
    message.From = new MailAddress(from);            
    foreach (string email in user_emails)
    {
        message.To.Add(new MailAddress(email));
    }            
    if (back_office_emails != null)
    {
        foreach (string email in back_office_emails)
        {
            message.Bcc.Add(new MailAddress(email));
        }
    }
    message.Subject = subject;
    message.Body = body;
    message.BodyEncoding = System.Text.Encoding.UTF8;
    return message;
}

protected virtual void SendEmailTemplate(string body, string from, string[] user_emails, string[] back_office_emails, string subject)
{
    MailMessage message = GetMailMessage(body, from, user_emails, back_office_emails, subject);
    SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SmtpClient"]);
    client.Send(message);
}

Solution:

AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(body.Trim(), new ContentType("text/html; charset=UTF-8"));
plainTextView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
message.AlternateViews.Add(plainTextView);

Because you are setting your message.BodyEncoding to System.Text.Encoding.UTF8 , the transfer encoding is automatically set to Base64. ( source in remarks section )

Depending on the reason why you need to have Quoted-printable transfer encoding, you will need to adjust your MailMessage object accordingly to have the transfer encoding set to Quoted-printable.

More reading can be done here

When using .NET 4.5 or better, it should be possible to use

message.BodyTransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;

See https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage.bodytransferencoding?view=netframework-4.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM