电子邮件与公司域名

时间:2015-11-10 05:19:29

标签: excel vba email

我正在尝试创建一个使用Google服务器但公司域的VBA脚本。一个典型的例子是firstname@company.com

我使用下面的代码,但如果我使用的域名不是gmail,则会给我一个错误。我想要求用户输入他们的登录信息(用户名和密码)。

Sub SendGMail()

' Object creation
Set objMsg = CreateObject("CDO.Message")
Set msgConf = CreateObject("CDO.Configuration")

' Server Configuration
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = UserForm1.TextBox1.Value
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = UserForm1.TextBox2.Value
msgConf.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
msgConf.Fields.Update

' Email
objMsg.To = UserForm1.TextBox1.Value
objMsg.From = UserForm1.TextBox1.Value
objMsg.Subject = "Test send with Gmail account"
objMsg.HTMLBody = "HTML/Plain text message."
objMsg.Sender = "Mr. Name"

Set objMsg.Configuration = msgConf

' Send
objMsg.Send

' Clear
Set objMsg = Nothing
Set msgConf = Nothing 

End Sub

1 个答案:

答案 0 :(得分:-1)

您需要在运行代码之前添加Microsoft CDO Reference

工具 - >参考--->用于Windows 2000库的Microsoft CDO

Sub MailTest()

Dim Mail As New Message
Dim Config As Configuration

Set Config = Mail.Configuration

Config(cdoSendUsingMethod) = cdoSendUsingPort
Config(cdoSMTPServer) = "smtp.gmail.com"
Config(cdoSMTPServerPort) = 25
Config(cdoSMTPAuthenticate) = cdoBasic
Config(cdoSMTPUseSSL) = True
Config(cdoSendUserName) = InputBox("EnterUsername")
' Otherwise if you use text box
'config(cdoSendUserName) = UserForm1.TextBox1.Text
Config(cdoSendPassword) = InputBox("Password")
' Otherwise if you use text box
'config(cdoSendUserName) = UserForm1.TextBox2.Text
Config.Fields.Update


Mail.To = "yahoo44@gmail.com"
Mail.From = Config(cdoSendUserName)
Mail.Subject = "Email Subject"
Mail.HTMLBody = "<b> mail body </b>"
Mail.Sender = " MRSender"

  Mail.Send
  MsgBox "mail has been sent"

End Sub