更改电子表格时使用Outlook从Excel发送自动电子邮件

时间:2015-07-09 13:44:01

标签: excel vba email excel-vba outlook

我在让Outlook通过Excel电子表格发送电子邮件时遇到问题。使用Outlook 2013和Gmail时没有问题但是当我使用具有唯一域(someEmail@CreatedDomain.mil)的先前版本(2010)时,我收到错误。我想说它是因为域名,但我不确定。以下是我在网上找到的代码。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)

    '-----AUTOMATIC EMAIL GENERATION-----------------------
    Dim answer As String

    answer = MsgBox("Saving this document will send an email to the database director and close the database. Are you sure you want to save?", _
        vbYesNo, "Save confirmation")
    '    Above code informs the user
    '    that an automated email will be sent to the database
    '    director and prompts them if they are ready to save

    'Code uses the users answer to either carryout the generated email process or to not save the changes.
    If answer = vbNo Then Cancel = True
    If Cancel = True Then Exit Sub
    If answer = vbYes Then

    'Connects to outlook and retrieves information needed to create and send the email.
    Set OutlookApp = CreateObject("Outlook.Application")
    Set OlObjects = OutlookApp.GetNamespace("MAPI")
    Set newmsg = OutlookApp.CreateItem(olMailItem)

    'Contains the email address of the person receiving the email.
    newmsg.Recipients.Add ("roman.hope.ctr@navy.mil")
    newmsg.Subject = "Automated email from excel database" 'Sets the automated subject line to the email
    newmsg.Body = "There has been a change to the excel database from the person sending linked to this email."
    'Above code has the body of the automated email

    'sets the email to "display" in the background then sends it in the next line of code (all in the background).
    newmsg.Display
    newmsg.Send 'sends the email

    'Displays a confirmation that the email has been sent.
    MsgBox "The email has been successfully sent", , "Email confirmation"
    '    ActiveWorkbook.Save

    End If
End Sub ' End of function

2 个答案:

答案 0 :(得分:2)

我已经想到了这个问题,而不是代码,而是我所在的网络。

网络具有自动电子邮件保护功能,可阻止所有应用程序发送自动通用电子邮件。

感谢大家的帮助。

答案 1 :(得分:1)

对于Outlook 2010,我总是使用这种语法,就像一个魅力,甚至不需要命名空间。

Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = "somebody@something.com"
    .CC = ""
    .BCC = ""
    .Subject = "YOUR SUBJECT"
    .HTMLBody = "your text as html"
    '.Attachments.Add ("path\filema.xsl") 'uncomment for attachment
    '.Display 'uncomment for display
    .Send

End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing

我没有尝试使用Outlook 2013,但在2010年,这会将电子邮件发送为有意。 如果您的Outlook中有多个邮件accs,则可能需要进行一些调整以选择正确的邮件。 它应该工作,因为CreateItem(0)通常总是一个新邮件,除非Microsoft没有按预期工作。

您也可以将.HTMLBody更改为.Body并且它应该可以使用,我只是喜欢我的邮件的HTML格式,因为这样您就可以轻松地在正文中使用附件。