简体   繁体   中英

Sending multipart email in ASP.NET with System.Net.Mail - received email has no body

I'm very confused about a problem with sending multipart emails in ASP.NET. I'm using code which I'm sure has worked before, but the received email appears to have no body.

The key bit of code is this:

message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, null, MediaTypeNames.Text.Plain));
message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html));

I can verify that plainBody is valid text and htmlBody is valid HTML. Apart from this I'm creating a very simple MailMessage with subject, from and to. I'm not setting any other properties of MailMessage and I'm sending with the standard System.Net.Mail.SmtpClient using Google credentials I've used many times before.

When the email arrives it appears to be completely empty.

If I replace the above two lines with the following (no other changes) then the HTML email arrives correctly.

message.Body = htmlBody;
message.IsBodyHtml = true;

So what could be the cause of my empty emails? I've tried simplifying the HTML right down to a single word wrapped in <b> tags so it's not related to the body content and, as I say, I've used similar code many times before with no problems. I've tested receipt of the emails in GMail and Office 365, both with same result.

Suggestions very welcome.

Why don't you break that piece of the code into two objects.

AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);

Put a break point in the second line and see whats in the alternate object. Maybe that might give you a little more insight into what's going on in your code.

You cannot set the mail with two different bodies. Since one of the parts is HTML, you need to treat all mail as HTML, just appending the plaintext normally - since the plaintext has no HTML encode inside, the text will appear as plaintext.

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