在asp.net mvc 5中发送带有附件PDF问题的电子邮件

时间:2018-11-10 19:12:19

标签: c# asp.net asp.net-mvc smtp

我正在尝试发送附有pdf的电子邮件,我的pdf是字节数组。当我尝试发送邮件(无pdf)时,它会显示

  

消息= SMTP服务器需要安全连接,或者客户端未通过身份验证。服务器响应为:5.5.1需要身份验证。了解更多信息

我的代码是`string senderEmail = System.Configuration.ConfigurationManager.AppSettings [“ SenderEmail”]。ToString();                 字符串senderPassword = System.Configuration.ConfigurationManager.AppSettings [“ SenderPassword”]。ToString();

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.Timeout = 100000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(senderEmail, senderPassword);

            MailMessage mailMassege = new MailMessage(senderEmail, toEmail, subject, body);
            mailMassege.IsBodyHtml = true;
            mailMassege.BodyEncoding = Encoding.UTF8;


            client.Send(mailMassege);`

我的pdf是字节数组 byte[] applicationPDFData = actionResult.BuildPdf(ControllerContext); System.IO.File.WriteAllBytes(filePath + "/hello.pdf", applicationPDFData);

我想用此pdf发送邮件。 预先感谢

1 个答案:

答案 0 :(得分:0)

您必须创建一个附件并将其附加到邮件Attachemnts列表中。 这是一个例子:

byte[] applicationPDFData = actionResult.BuildPdf(ControllerContext);
Attachment attPDF = new Attachment(new MemoryStream(applicationPDFData), name);

EmailMessage emailMessage = new EmailMessage();
emailMessage.To.Add( new EmailRecipient( toEmail ) );
emailMessage.Subject = subject;
emailMessage.Body = body;
emailMessage.Attachments.Add( attPDF );

成绩 gy