![](/img/trans.png)
[英]Can not change the display name of From email through smtp.office365.com using C# SmtpClient
[英]Unable to send email from Office 365 using c# SmtpClient
嘗試使用 SmtpClient 從我在 c# 中的 winforms 應用程序發送電子郵件。 通過這篇 MS 文章,它應該可以工作。 我搜索了許多論壇等,但沒有找到任何解決方案。 該錯誤消息似乎表明客戶端未通過身份驗證。 密碼是正確的,我已經以這個用戶的身份登錄了密碼,沒問題。 2FA 已開啟,但 htis 不應該妨礙它嗎?
我檢查過的東西都到位了
代碼
var userName = "user@domain.onmicrosoft.com";
var password = "password";
var msg = new MailMessage();
msg.To.Add(new MailAddress("user@gmail.com"));
msg.From = new MailAddress(userName);
msg.Subject = "Test Office 365 Account";
msg.Body = "Testing email using Office 365 account.";
msg.IsBodyHtml = true;
var client = new SmtpClient{
Host = "smtp.office365.com",
Credentials = new System.Net.NetworkCredential(userName, password),
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = true
};
client.Send(msg);
例外
MAIL KIT 實現(建議 vasily.sib)
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test User", "user@domain.onmicrosoft.com"));
message.To.Add(new MailboxAddress("Gmail User", "testuser@gmail.com"));
message.Subject = "test";
message.Body = new TextPart("plain")
{
Text = @"test"
};
var client = new SmtpClient(new ProtocolLogger("imap.log"));
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.office365.com", 587, SecureSocketOptions.Auto); //this is fine and it connects
var clientAuthenticationMechanisms = client.AuthenticationMechanisms;
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("user@domain.onmicrosoft.com", "password"); // this is where it fails with Authentication Failure
client.Send(message);
client.Disconnect(true);
郵件套件日志輸出
Connected to smtp://smtp.office365.com:587/?starttls=when-available
S: 220 SYCP282CA0015.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 25 Nov 2019 04:49:36 +0000
C: EHLO [192.168.2.50]
S: 250-SYCP282CA0015.outlook.office365.com Hello [58.6.92.82]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [192.168.2.50]
S: 250-SYCP282CA0015.outlook.office365.com Hello [58.6.92.82]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH LOGIN XOAUTH2
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: AUTH LOGIN
REMOVED BASE64 DATA (password, login)
S: 535 5.7.3 Authentication unsuccessful [SYCP282CA0015.AUSP282.PROD.OUTLOOK.COM]
解決了。 正是 2FA 阻止了它的發生。 關掉它,它起作用了
我今天遇到了同樣的問題。 Office365 也需要 TLS 連接。 因此,您應該將以下代碼添加到您的代碼中
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.