Wednesday, February 5, 2014

Send automatic email using VBA

Here I have shared the simple code for sending an automatic email using Macros. It can be excuted in all primary products of the Microsoft. you can send emails to recipient from excel data too. Basically To address, subject and HTMLBody are the apex elements. assign those values and shoot the emails using below simple syntax

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 = "Macroraman@example.com" 'To address
.CC = ""
.BCC = ""
.Subject = "Assignment"
.HTMLBody = "Hi"
'.Attachments.Add ActiveWorkbook.FullName (for active book)
'.Attachments.Add ("D:\Book1.xls") (for external book)
'.Display (to see the message window)
'.Save (to save as Draft)
.Send
End With
Set OutMail = Nothing
Set OutApp = Nothing

You may face one dificulty when you run the code due to your Outlook security setting. It may ask your acceptance through popup. to avoid such popups follow below steps

For older window versions
Tools menu -> Options -> Security tab
uncheck and save "Warn me when other applications try to send mail as me" check box.

For latest Window versions
File - > Options -> Trust Center -> Trust Center settings -> Programmatic Access
Uncheck and save warning option

In office/secured environment, If you are unable to change the security settings, you can use less equivalent code instead of ".Send"
.Display
Application.Wait (Now + TimeValue("0:00:02"))
Application.SendKeys "%s"

which means your are executing as manual operation

0 comments:

Post a Comment

You Can use HTML code once it converted to NCcode by NCode converter