Office 365发送电子邮件(VBA)的解决scheme

我已经search了几个月,但仍然得到解决scheme。

使用CDO为Office365发送电子邮件不起作用。

在这里输入图像说明

获得像传输错误无法连接或身份validation失败。

想共享解决scheme,我build立解决发送电子邮件通过Office365 SMTP。

1)我们需要为Excel创build一个自定义DLL

2)将DLL作为安装程序打包,然后安装到计算机中(如果您希望共享您的macros)

3)通过Excel VBA消耗DLL

让我们开始吧:

1)为Excel创build自定义DLL(源代码)

重要的一点是使所有的工作都是领域

client.Credentials = new System.Net.NetworkCredential(Email, Password, "outlook.com"); 

如果域错误或空,它将无法正常工作。

 using System.Net.Mail; namespace Eric_Library { public class SMTP { public string oSMTP(string Email, string Password, string subject, string htmlBody, string[] Attachments, string To, string Cc, string Bcc) { Email = Email.Trim(); try { if (!Email.EndsWith("@outlook.com", StringComparison.CurrentCultureIgnoreCase)) throw new Exception("Your domain is not matching"); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.office365.com"); client.TargetName = "STARTTLS/smtp.office365.com"; client.UseDefaultCredentials = false; //Domain name can be "company.com" or "outlook.com" or etc client.Credentials = new System.Net.NetworkCredential(Email, Password, "outlook.com"); client.EnableSsl = true; client.Port = 587; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new MailAddress(Email); msg.CC.Add(Email); msg.Subject = subject; msg.Body = htmlBody; msg.IsBodyHtml = true; if (string.IsNullOrEmpty(To)) throw new Exception("To cannot be blank"); else { To.Replace(";", ","); msg.To.Add(To); } if (!string.IsNullOrEmpty(Cc)) { Cc.Replace(";", ","); msg.CC.Add(Cc); } if (!string.IsNullOrEmpty(Bcc)) { Bcc.Replace(";", ","); msg.Bcc.Add(Bcc); } if (Attachments.Count() > 0) { foreach (var item in Attachments) { if (!string.IsNullOrEmpty(item)) { System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(item); msg.Attachments.Add(attachment); } } } client.Send(msg); return "Message Sent : " + DateTime.Now.ToString(); } catch (Exception ex) { return ex.Message; } } } 

}

***请记住检查注册COM互操作,否则您将无法将其添加为VBA中的参考 在这里输入图像说明

2)将DLL打包为安装程序(我的项目名称是Office365 SMTP库)创build安装程序非常简单,记住将这两个文件分别放入安装程序,然后构build它。

在这里输入图像说明

3)通过Excel VBA使用DLL进入程序目录,然后selecttlb文件作为参考。

在这里输入图像说明

– >如果您将macros分享给其他用户,请确保他们已经安装了DLL

– >他们不需要再添加引用,Excel会自动查找。

现在你可以使用DLL了

 Private Sub test_oMail() Dim oMsg As Office365_SMTP_Library.SMTP Set oMsg = New Office365_SMTP_Library.SMTP Dim nArr_Attach() As String ReDim nArr_Attach(1) nArr_Attach(0) = "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg" nArr_Attach(1) = "C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" Debug.Print oMsg.oSmtp("email", "password", _ "Testing Subject", "<p>First Paragraph</p><p>Second Paragraph</p>", _ nArr_Attach, "TO", "CC", "BCC") End Sub 

– >将附件作为数组传递,以便尽可能多地使用 – >但是请记住,Office 365每个电子邮件的上限为30MB

谢谢