Sample code for 30+ languages & platforms
Xbase++

Send HTML Email with Attachments

See more SMTP Examples

Demonstrates how to send an HTML email with file attachments.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oMailman
LOCAL oEmail
LOCAL cContentIdStarfish
LOCAL oSbHtml
LOCAL nNumReplacements
LOCAL cContent

nSuccess := 0

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

oMailman := CreateObject("Chilkat.MailMan")

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

oMailman:SmtpUsername := "MY-SMTP-USERNAME"
oMailman:SmtpPassword := "MY-SMTP-PASSWORD"

oMailman:StartTLS := 1
oMailman:SmtpPort := 587

//  Create a new email object
oEmail := CreateObject("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.
cContentIdStarfish := oEmail:AddRelatedFile("qa_data/jpg/starfish.jpg")
IF (oEmail:LastMethodSuccess != 1)
    ? oEmail:LastErrorText
    oMailman:destroy()
    oEmail:destroy()
    RETURN
ENDIF

//  The src attribute for the image tag is set to the contentIdStarfish:
oSbHtml := CreateObject("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>')
nNumReplacements := oSbHtml:Replace("CONTENT_ID_STARFISH", cContentIdStarfish)

oEmail:AddHtmlAlternativeBody(oSbHtml:GetAsString())

//  Finally, add some attachments to the email.
//  Add a file attachment.
nSuccess := oEmail:AddFileAttachment2("qa_data/pdf/fishing.pdf", "application/pdf")
IF (nSuccess != 1)
    ? oEmail:LastErrorText
    oMailman:destroy()
    oEmail:destroy()
    oSbHtml:destroy()
    RETURN
ENDIF

//  Add an attachment where the content is contained in a string.
cContent := "This is the content of the 2nd attached file."
oEmail:AddStringAttachment("someText.txt", cContent)

//  Send the HTML email.
nSuccess := oMailman:SendEmail(oEmail)
IF (nSuccess != 1)
    ? oMailman:LastErrorText
    oMailman:destroy()
    oEmail:destroy()
    oSbHtml:destroy()
    RETURN
ENDIF

nSuccess := oMailman:CloseSmtpConnection()
IF (nSuccess != 1)
    ? "Connection to SMTP server not closed cleanly."
ENDIF

? "HTML email with attachments sent!"

oMailman:destroy()
oEmail:destroy()
oSbHtml:destroy()