Sample code for 30+ languages & platforms
AutoIt

Send HTML Email with Attachments

See more SMTP Examples

Demonstrates how to send an HTML email with file attachments.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

; This example requires the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.

$oMailman = ObjCreate("Chilkat.MailMan")

$oMailman.SmtpHost = "smtp.my-starttls-mail-server.com"

$oMailman.SmtpUsername = "MY-SMTP-USERNAME"
$oMailman.SmtpPassword = "MY-SMTP-PASSWORD"

$oMailman.StartTLS = True
$oMailman.SmtpPort = 587

; Create a new email object
$oEmail = ObjCreate("Chilkat.Email")
$oEmail.Subject = "Test SMTP API to Send HTML Email with Attachments"
$oEmail.From = "Joe Programmer <joe@my-starttls-mail-server.com>"
$oEmail.AddTo("Chilkat Support","support@chilkatsoft.com")

; Add a plain-text alternative body, which will likely never be seen.
; (It is shown if the receiving email client is incapable of displaying HTML email.)
$oEmail.AddPlainTextAlternativeBody("This is a plain-text alternative body...")

; Our HTML will include an image, so add the related image here.
Local $sContentIdStarfish = $oEmail.AddRelatedFile("qa_data/jpg/starfish.jpg")
If ($oEmail.LastMethodSuccess <> True) Then
    ConsoleWrite($oEmail.LastErrorText & @CRLF)
    Exit
EndIf

; The src attribute for the image tag is set to the contentIdStarfish:
$oSbHtml = ObjCreate("Chilkat.StringBuilder")
$oSbHtml.Append("<html><body><p>This is an HTML email with an embedded image.</p>")
$oSbHtml.Append("<p><img src=""cid:CONTENT_ID_STARFISH"" /></p></body></html>")
Local $iNumReplacements = $oSbHtml.Replace("CONTENT_ID_STARFISH",$sContentIdStarfish)

$oEmail.AddHtmlAlternativeBody($oSbHtml.GetAsString())

; Finally, add some attachments to the email.
; Add a file attachment.
$bSuccess = $oEmail.AddFileAttachment2("qa_data/pdf/fishing.pdf","application/pdf")
If ($bSuccess <> True) Then
    ConsoleWrite($oEmail.LastErrorText & @CRLF)
    Exit
EndIf

; Add an attachment where the content is contained in a string.
Local $sContent = "This is the content of the 2nd attached file."
$oEmail.AddStringAttachment("someText.txt",$sContent)

; Send the HTML email.
$bSuccess = $oMailman.SendEmail($oEmail)
If ($bSuccess <> True) Then
    ConsoleWrite($oMailman.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oMailman.CloseSmtpConnection()
If ($bSuccess <> True) Then
    ConsoleWrite("Connection to SMTP server not closed cleanly." & @CRLF)
EndIf

ConsoleWrite("HTML email with attachments sent!" & @CRLF)