我试图使用ASP.NET Core3.1和C#发送带有附件的电子邮件。 最初从数据库加载数据并将其作为内存流附加到邮件中,我可以接收邮件,但附件中的内容总是空白的。
我试过文本格式,CSV格式,PDF格式,我收到的每一个附件都是空白的,不知道我做错了什么,下面是代码,
public void SendEmail(DataTable table)
{
MemoryStream _oMemStream = new MemoryStream();
StreamWriter sw = new StreamWriter(_oMemStream);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName.ToString() + ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < row.ItemArray.Length; i++)
{
string rowText = row.ItemArray[i].ToString();
sw.Write(rowText + ",");
}
sw.WriteLine();
}
EmailDetailsModel emDetails = new EmailDetailsModel();
emDetails.Body = "Body Of the Mail For Email Functionality";
emDetails.Email = "xxxx";
emDetails.To = "xxx";
emDetails.Subject = "Testing Email Functionality";
emDetails.Password = "xxx";
using (MailMessage mm = new MailMessage(emDetails.Email, emDetails.To))
{
_oMemStream.Position = 0;
mm.Subject = emDetails.Subject;
mm.Body = emDetails.Body;
var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
var reportAttachment = new Attachment(_oMemStream, contentType);
reportAttachment.ContentDisposition.FileName = "yourFileName.pdf";
mm.Attachments.Add(reportAttachment);
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(emDetails.Email, emDetails.Password);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = xx;
smtp.Send(mm);
ViewBag.Message = "Email sent.";
}
}
}
谢谢你的建议
您是否尝试在邮件消息生成之前添加sw.close();
?