使用企业邮箱发送运行时生成的PDF附件邮件失败求助
企业邮箱发送动态生成PDF附件邮件的认证错误排查与解决
问题描述
使用企业邮箱发送带运行时生成PDF附件的邮件时,出现以下错误:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at
或
Failure sending mail
相关代码如下:
protected void BtnSendEmail_Click(object sender, EventArgs e) { Send_Email("moin.softwin@gmail.com","This is a mail with an attchment!","hello There, Have a good day. I have sent u an email with an attchment!"); } protected string Bind_Invoice() { string op = null; try { con = new SqlConnection(CommonClass.Get_DB_Path); con.Open(); cmd = new SqlCommand("BIND_PURCHASE_INVOICE", con); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 10000; cmd.Parameters.AddWithValue("@USER", Session["username"].ToString()); SqlParameter RuturnValue = new SqlParameter("@RETVAL", SqlDbType.VarChar, 18000); RuturnValue.Direction = ParameterDirection.Output; cmd.Parameters.Add(RuturnValue); cmd.ExecuteNonQuery(); op = cmd.Parameters["@RETVAL"].Value.ToString(); cmd.Dispose(); con.Close(); } catch (Exception ex) { if (ex.Message != null) { op = ex.Message; con.Close(); } } return op; } protected void Send_Email(string ToAddress, string MailSubject, string MailBody) { try { MailMessage message = new MailMessage(); message.To.Add(ToAddress);// Email-ID of Receiver message.Subject = MailSubject;// Subject of Email message.From = new System.Net.Mail.MailAddress("MYUSERNAME");// Email-ID of Sender message.IsBodyHtml = true; string PDFdata = Bind_Invoice(); MemoryStream file = new MemoryStream(PDFGenerate(PDFdata, Server.MapPath("img/bg.jpg")).ToArray()); file.Seek(0, SeekOrigin.Begin); Attachment data = new Attachment(file, "RunTime_Attachment.pdf", "application/pdf"); ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.DateTime.Now; disposition.ModificationDate = System.DateTime.Now; disposition.DispositionType = DispositionTypeNames.Attachment; message.Attachments.Add(data);//Attach the file message.Body = MailBody; SmtpClient SmtpMail = new SmtpClient(); SmtpMail.Host = "MY HOST ADDRESS";//name or IP-Address of Host used for SMTP transactions SmtpMail.Port = 465;//Port for sending the mail SmtpMail.Credentials = new System.Net.NetworkCredential("MYUSERNAME", "MYPASS");//username/password of network, if apply SmtpMail.DeliveryMethod = SmtpDeliveryMethod.Network; SmtpMail.EnableSsl = true; SmtpMail.UseDefaultCredentials = false; SmtpMail.ServicePoint.MaxIdleTime = 0; SmtpMail.ServicePoint.SetTcpKeepAlive(true, 2000, 2000); message.BodyEncoding = Encoding.Default; message.Priority = MailPriority.High; SmtpMail.Send(message); //Smtpclient to send the mail message Response.Write("Email has been sent !"); } catch (Exception ex) { Response.Write("Failed !"); } } private MemoryStream PDFGenerate(string message, string ImagePath) { MemoryStream output = new MemoryStream(); Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, output); pdfDoc.Open(); Paragraph Text = new Paragraph(message); pdfDoc.Add(Text); byte[] file; file = System.IO.File.ReadAllBytes(ImagePath); iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(file); jpg.ScaleToFit(550F, 200F); pdfDoc.Add(jpg); pdfWriter.CloseStream = false; //pdfDoc.Close(); output.Position = 0; return output; }
解决方案
1. 校正SMTP基础配置
- 确认服务器地址:替换
MY HOST ADDRESS为企业邮箱官方提供的SMTP域名(如腾讯企业邮为smtp.exmail.qq.com,阿里企业邮为smtp.mxhichina.com),禁止使用错误的IP或非官方域名。 - 匹配端口与加密规则:端口465对应SSL加密,但部分企业邮箱要求使用587端口(STARTTLS协议),需查阅企业邮箱文档确认。若切换到587端口,保持
EnableSsl = true即可。
2. 修复认证信息问题
- 使用完整邮箱用户名:企业邮箱SMTP认证的用户名必须是完整邮箱地址(如
user@company.com),不能仅填前缀,替换代码中所有MYUSERNAME为完整邮箱。 - 验证密码有效性:若企业开启了二次验证,需使用应用专用密码而非原登录密码;未开启则确保
MYPASS是当前有效的邮箱登录密码。 - 调整认证参数顺序:确保
UseDefaultCredentials = false在设置Credentials之前执行,避免.NET默认覆盖自定义认证信息,修改代码片段:SmtpMail.UseDefaultCredentials = false; SmtpMail.Credentials = new System.Net.NetworkCredential("完整邮箱地址", "密码/应用专用密码");
3. 优化代码细节
- 捕获完整异常信息:修改catch块输出详细错误,定位问题根源:
catch (Exception ex) { Response.Write($"发送失败:{ex.Message},详情:{ex.InnerException?.Message}"); } - 释放PDF资源:取消
PDFGenerate方法中pdfDoc.Close();的注释,确保PDF文档资源正确释放,避免内存流损坏导致发送失败。 - 统一编码格式:将
message.BodyEncoding = Encoding.Default改为Encoding.UTF8,避免中文乱码或编码不兼容问题。
4. 检查企业邮箱权限
- 联系管理员确认该账号是否被允许使用SMTP服务,以及服务器IP是否在邮箱的发送白名单内。
- 登录企业邮箱后台,确认SMTP服务是否已手动开启(部分云邮箱默认关闭该功能)。
内容的提问来源于stack exchange,提问作者USER0349579345
相关产品推荐
相关产品推荐

