使用office365发送电子邮件

时间:2017-05-13 03:01:45

标签: c# asp.net smtp sendmail smtpclient

我正在尝试使用office365发送电子邮件,但面临此问题:

其他信息:SMTP服务器需要安全连接,或者客户端未经过身份验证。服务器响应是:5.7.57 SMTP;客户未通过身份验证,以便在MAIL FROM [MA1PR01CA0073.INDPRD01.PROD.OUTLOOK.COM]期间发送匿名邮件

我发送电子邮件的代码是:

 var fromAddress = new MailAddress("email", "Relay");
        var toAddress = new MailAddress("email");
        const string fromPassword = "password";
        const string subject = "Subject";
        const string body = "Body";

        var smtp = new SmtpClient
        {
            Host = "smtp.office365.com",
            Port = 587,
            EnableSsl = true,

            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            TargetName = "STARTTLS/smtp.office365.com",
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword, "islandenergyservices.com")
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }

2 个答案:

答案 0 :(得分:1)

我以前遇到过这个问题。这是一个愚蠢的小怪癖与订单,你在客户端设置属性 - 你必须在做其他任何事情之前设置 DefaultCredentials 然后你会没事的

请参阅this回答。

答案 1 :(得分:0)

我在以下方面取得了成功:

# Sending an email from PowerShell 5.1 script through outlook.office365.com
#
# 1. Create an encrypted password file
#   PS > Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -FilePath <passwordfile>
#   This will prompt you for a password, encrypt and save in <passwordfile>
# 2. Obtain Outlook Office365 SMTP server name.
#   Go to your ISP and find the value of the MX record. For example <yourdomain>.mail.protection.outlook.com
# 3. If after running the script you get this error:
#   Send-MailMessage : Mailbox unavailable. The server response was: 5.7.606 Access denied, banned sending IP [X.X.X.X].
#   You will need to delist your IP by going here: https://sender.office.com/
#   Note:  Removing you IP from the block list could take up to 30 minutes.
#
$User = "<SMPT loging username>"
$PasswordFile = "<passwordfile>"
$SMTPCredentials=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString)
$EmailTo = "<to email address>"
$EmailFrom = "<from email address>"
$Subject = "<email subject>" 
$Body = "<email body>" 
$SMTPServer = "<Outlook STMP Server from MX record>"
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port 25 -Credential $SMTPCredentials -UseSsl