Sample code for 30+ languages & platforms
PowerBuilder

Add a Related File to an HTML Email

See more Email Object Examples

Demonstrates the Chilkat Email.AddRelatedFile method, which adds the contents of a local file as a related MIME resource and returns the generated Content-ID. The returned value is the bare Content-ID — no angle brackets and no cid: prefix — so if it returns CID-123@example, the HTML reference is cid:CID-123@example. Because the Content-ID is generated by the call, this example adds the image first, then builds the HTML body in a StringBuilder — using a placeholder in the <img> tag that is replaced with the returned Content-ID — and passes the result to SetHtmlBody.

Background: To embed an image so it displays inside an HTML email (rather than being downloaded from a web server), you add it as a "related" part and reference it from the HTML with a cid: URL that matches the part's Content-ID. Since Chilkat assigns that ID when you add the file, the natural order is: add the related file, capture the returned ID, then build the <img src="cid:..."> reference from it. A StringBuilder makes assembling and updating the HTML convenient.

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
oleobject loo_Email
string ls_Cid
oleobject loo_SbHtml
integer li_NumReplaced

//  Demonstrates the AddRelatedFile method, which adds a local file as a related MIME
//  resource (such as an image displayed by an HTML body) and returns the generated
//  Content-ID.  The HTML references the item using cid:<Content-ID>.

loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")
if li_rc < 0 then
    destroy loo_Email
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Email.Subject = "Email with a related image"

//  Add the image file as a related item first.  The return value is the bare Content-ID
//  (no angle brackets and no "cid:" prefix).
ls_Cid = loo_Email.AddRelatedFile("qa_data/images/logo.png")
if loo_Email.LastMethodSuccess = 0 then
    Write-Debug loo_Email.LastErrorText
    destroy loo_Email
    return
end if

//  Build the HTML body in a StringBuilder, using a placeholder where the image's
//  Content-ID will go.
loo_SbHtml = create oleobject
li_rc = loo_SbHtml.ConnectToNewObject("Chilkat.StringBuilder")

loo_SbHtml.Append("<html><body><img src=~"cid:PLACEHOLDER_CID~"/></body></html>")

//  Replace the placeholder with the actual Content-ID returned by AddRelatedFile.
li_NumReplaced = loo_SbHtml.Replace("PLACEHOLDER_CID",ls_Cid)

//  Set the HTML body from the StringBuilder result.
loo_Email.SetHtmlBody(loo_SbHtml.GetAsString())

Write-Debug "Related Content-ID = " + ls_Cid
Write-Debug "NumRelatedItems = " + string(loo_Email.NumRelatedItems)

//  Note: The path "qa_data/images/logo.png" is a relative local filesystem path,
//  relative to the current working directory of the running application.


destroy loo_Email
destroy loo_SbHtml