办公室365发送电子邮件(VBA)的解决方案
问题描述:
答
想共享解决方案,我建立解决发送电子邮件通过Office365 SMTP。
1)我们需要建立一个自定义DLL为Excel
2)包装的DLL作为安装程序,然后安装在计算机(如果你想分享你的宏)
3)消费DLL通Excel的VBA
我们得到启动:
1)为Excel创建自定义的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 Library) 创建安装程序非常简单,记住将这两个文件分别放入安装程序,然后构建它。
3)消费DLL直通Excel的VBA 进入程序目录,然后选择TLB文件,将其添加为参考。
- >如果您共享您的宏其他用户,确保他们有安装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
- >传入附件作为数组,这样就可以有尽可能多如你所愿 - >但要记住的最大限制是30MB Office365每封邮件
谢谢