C# 在 .net 中发送 SMTP 电子邮件测试 Microsoft Office 365

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15899213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:21:36  来源:igfitidea点击:

Send SMTP email testing Microsoft Office 365 in .net

c#exchange-serveroffice365system.net.mail

提问by user166013

i have a mail account on the Exchange Online service. Now i'm trying to test if i am able to send mails to customers ( on varoius domains and on Microsoft Office 365) through c# application

我在 Exchange Online 服务上有一个邮件帐户。现在我正在尝试测试我是否能够通过 c# 应用程序向客户发送邮件(在各种域和 Microsoft Office 365 上)

I tried implementing the below code but i am getting the error

我尝试实现以下代码,但出现错误

"The remote certificate is invalid according to the validation procedure."

“根据验证程序,远程证书无效。”

MailMessage mail = null;                
mail = new MailMessage();

string[] strToList = "[email protected]"              
foreach (string strID in strToList)
{
    if (strID != null)
    {
        mail.To.Add(new MailAddress(strID));
    }
}

mail.From = "[email protected]";
mail.Subject = "testing"
mail.IsBodyHtml = true;
mail.Body = "mail body";

SmtpClient client = new SmtpClient("smtp.outlook.office365.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
NetworkCredential cred = new System.Net.NetworkCredential("[email protected]", "mypassword");
client.Credentials = cred;
client.Send(mail);

Please advice if i am doing anything wrong. Thanks a lot in advance.

如果我做错了什么,请提出建议。非常感谢。

回答by Piotr Stapp

Try to use:

尝试使用:

ServicePointManager.ServerCertificateValidationCallback = 
    (sender, certificate, chain, sslPolicyErrors) => true;

This code will allow you to accept invalid certificates.

此代码将允许您接受无效证书。

As Ori Nachum mention in the comment: this is a very BAD practice, and should only use for testing purposes. It is a security risk!

正如 Ori Nachum 在评论中提到的:这是一种非常糟糕的做法,只能用于测试目的。这是一个安全风险!

回答by hiFI

The Error

错误

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated

SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.7.1 客户端未通过身份验证

often happens when associated user account password is expired or account is locked. Try set "Never expire user password" in Active Directory, if it does not breach your company password policy :) This happened to me while testing with o365 Exchange Online A/c.

通常发生在关联的用户帐户密码过期或帐户被锁定时。尝试在 Active Directory 中设置“永不过期用户密码”,如果它不违反您公司的密码策略:) 在使用 o365 Exchange Online A/c 进行测试时发生了这种情况。

回答by Zakos

this works for me ( edited from source)

这对我有用(从源代码编辑)



   ThreadPool.QueueUserWorkItem(t =>
            {
                SmtpClient client = new SmtpClient("smtp.office365.com",587);
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
                MailAddress from = new MailAddress("[email protected]", String.Empty, System.Text.Encoding.UTF8);
                MailAddress to = new MailAddress("[email protected]");
                MailMessage message = new MailMessage(from, to);
                message.Body = "The message I want to send.";
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = "The subject of the email";
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                // Set the method that is called back when the send operation ends.
                client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                // The userState can be any object that allows your callback 
                // method to identify this send operation.
                // For this example, I am passing the message itself
                client.SendAsync(message, message);
            });

        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the message we sent
            MailMessage msg = (MailMessage)e.UserState;

            if (e.Cancelled)
            {
                // prompt user with "send cancelled" message 
            }
            if (e.Error != null)
            {
                // prompt user with error message 
            }
            else
            {
                // prompt user with message sent!
                // as we have the message object we can also display who the message
                // was sent to etc 
            }

            // finally dispose of the message
            if (msg != null)
                msg.Dispose();
        }

回答by Benjamin Talmard

Try smtp.office365.com instead of smtp.outlook.office365.com

尝试 smtp.office365.com 而不是 smtp.outlook.office365.com

回答by Joe Frank

In some cases the TLS authentication may cause problems in using smtp.office365.com as SMTP from c#. Try the following line before the Send(msg) statement (overriding .TargetName):

在某些情况下,TLS 身份验证可能会导致将 smtp.office365.com 用作 c# 中的 SMTP 时出现问题。在 Send(msg) 语句之前尝试以下行(覆盖 .TargetName):

client.TargetName = "STARTTLS/smtp.office365.com";

This one works for me

这个对我有用

回答by Shashi Keshar

This is also best way to send Mail. I have tried it in my project and working fine.

这也是发送邮件的最佳方式。我已经在我的项目中尝试过并且工作正常。

 SmtpClient client = new SmtpClient("smtp.office365.com", 587);
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "sdsd@12345");
        MailAddress from = new MailAddress("From Address Ex [email protected]", String.Empty, System.Text.Encoding.UTF8);
        MailAddress to = new MailAddress("From Address Ex [email protected]");
        MailMessage message = new MailMessage(from, to);
        message.Body = "This is your body message";
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.Subject = "Subject";
        message.SubjectEncoding = System.Text.Encoding.UTF8;

        client.Send(message);

回答by Ori Nachum

Try setting:

尝试设置:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

It will ensure the Service's SecurityPoint is TLS.
Please notice an answer here offered setting

它将确保服务的 SecurityPoint 是 TLS。
请注意这里提供的设置的答案

ServicePointManager.ServerCertificateValidationCallback = 
    (sender, certificate, chain, sslPolicyErrors) => true;

May be good for testing purposes - but it's a major security risk!
Do not use with a prod account or in prod environment.

可能适用于测试目的 - 但这是一个主要的安全风险
不要使用 prod 帐户或在 prod 环境中使用。