You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ASP.Net通过Office365发送带附件SMTP邮件失败求助

Hey Gonzalo, let's break this down step by step to figure out why your Office 365 email with attachments isn't sending via ASP.NET. First off, your code snippet cuts off at msg.IsBody...—that's a crucial piece, but let's cover both code fixes and Office 365 configuration checks to cover all bases.

1. Fix & Complete Your Email Code

First, let's fill in the gaps and add the proper Office 365 SMTP configuration and attachment logic. Here's a full, working example:

using System.IO;
using System.Net;
using System.Net.Mail;

protected void sentmail(string sb)
{
    using (var msg = new MailMessage())
    {
        // Set core email details
        msg.To.Add(new MailAddress("myaccount@company.cl"));
        msg.From = new MailAddress("botmail@company.cl");
        msg.ReplyToList.Add("botmail@company.cl");
        msg.Subject = "Test Mail";
        msg.Body = sb.ToString();
        msg.IsBodyHtml = false; // Set to true if you're sending HTML content

        // Add attachment (adjust path and file type as needed)
        string attachmentFilePath = Server.MapPath("~/Attachments/test-document.pdf");
        if (File.Exists(attachmentFilePath))
        {
            var attachment = new Attachment(attachmentFilePath);
            msg.Attachments.Add(attachment);
        }
        else
        {
            // Log or handle missing file error
            throw new FileNotFoundException("Attachment file not found", attachmentFilePath);
        }

        // Configure Office 365 SMTP client
        using (var smtpClient = new SmtpClient("smtp.office365.com", 587))
        {
            smtpClient.Credentials = new NetworkCredential("botmail@company.cl", "Your_Office365_Password");
            smtpClient.EnableSsl = true;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            try
            {
                smtpClient.Send(msg);
                // Add success logic here (e.g., log, show message)
            }
            catch (Exception ex)
            {
                // Capture FULL error details (critical for debugging)
                string errorDetails = $"Send failed: {ex.Message}\nInner Exception: {ex.InnerException?.Message}";
                // Log this error or display it for troubleshooting
                throw new Exception(errorDetails, ex);
            }
        }
    }
}

Key Code Notes:

  • Office 365 SMTP Settings: Hardcoded to smtp.office365.com on port 587 with SSL enabled—this is non-negotiable for Office 365.
  • Attachments: Make sure the file path is accessible to your ASP.NET app (check permissions for the app pool identity if running on IIS).
  • Error Handling: Always capture the InnerException—it often reveals the real issue (like authentication failures or missing permissions).
2. Critical Office 365 Configuration Checks

More often than not, send failures are due to account settings, not code:

  • Multi-Factor Authentication (MFA): If your botmail@company.cl account uses MFA, your regular password won't work. You need to generate an App Password in your Office 365 account settings and use that instead.
  • SMTP Access Enabled: Verify SMTP is allowed for the account:
    1. Go to the Exchange Admin Center.
    2. Navigate to Recipients > Mailboxes.
    3. Select your botmail account, go to Mailbox Features > Email Connectivity.
    4. Ensure SMTP is enabled.
  • Domain SPF Record: If your emails are bouncing or going to spam, make sure your domain's SPF record includes include:spf.protection.outlook.com to validate Office 365 as a legitimate sender.
3. Debugging Steps to Narrow It Down
  • Test sending an email without attachments first—if that works, the issue is likely with your attachment path or file permissions.
  • Check your application logs for the full exception message (e.g., "Authentication failed" means wrong credentials/MFA issue; "File not found" means bad attachment path).
  • Verify the ASP.NET app pool identity has read access to the folder where your attachments are stored.

内容的提问来源于stack exchange,提问作者Gonzalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:21:11