简体   繁体   English

使用System.Net.Mail在ASP.NET中发送多部分电子邮件-收到的电子邮件没有正文

[英]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. 我对在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. 我可以验证plainBody是有效的文本,并且htmlBody是有效的HTML。 Apart from this I'm creating a very simple MailMessage with subject, from and to. 除此之外,我还创建了一个非常简单的MailMessage ,主题为from和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. 我没有设置MailMessage任何其他属性,而是使用以前使用过多次的Google凭据与标准System.Net.Mail.SmtpClient进行发送。

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. 如果我将以上两行替换为以下内容(无其他更改),则HTML电子邮件会正确到达。

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. 我曾尝试将HTML简化为一个用<b>标记包裹的单词,因此它与主体内容无关,而且正如我所说,我之前使用过类似的代码很多次而没有问题。 I've tested receipt of the emails in GMail and Office 365, both with same result. 我已经在GMail和Office 365中测试了电子邮件的接收,两者的结果相同。

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. 由于其中一部分是HTML,因此您需要将所有邮件都视为HTML,只是正常地添加纯文本-由于纯文本内部没有HTML编码,因此文本将显示为纯文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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