Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

后端 未结 8 578
悲&欢浪女
悲&欢浪女 2020-11-29 23:34

We are testing the new Office 365 beta, and i have a mail account on the Exchange Online service. Now I\'m trying to connect a LOB application that can send smtp emails from

8条回答
  •  一个人的身影
    2020-11-30 00:10

    In year of 2020, these code seems to return exception as

    System.Net.Mail.SmtpStatusCode.MustIssueStartTlsFirst or The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM

    This code is working for me.

                using (SmtpClient client = new SmtpClient()
                {
                    Host = "smtp.office365.com",
                    Port = 587,
                    UseDefaultCredentials = false, // This require to be before setting Credentials property
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential("alias@fulldomain.com", "password"), // you must give a full email address for authentication 
                    TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
                    EnableSsl = true // Set to avoid secure connection exception
                })
                {
    
                    MailMessage message = new MailMessage()
                    {
                        From = new MailAddress("alias@fulldomain.com"), // sender must be a full email address
                        Subject = subject,
                        IsBodyHtml = true,
                        Body = "

    Hello World

    ", BodyEncoding = System.Text.Encoding.UTF8, SubjectEncoding = System.Text.Encoding.UTF8, }; var toAddresses = recipients.Split(','); foreach (var to in toAddresses) { message.To.Add(to.Trim()); } try { client.Send(message); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }

提交回复
热议问题