Swift Requires Chilkat v11.0.0+
Swift
Add an attachment and an inline image
See more Email Object Examples
Add a file attachment from memory and embed an image in the HTML body using its Content-ID. Start with any email that has an HTML body, or use text-and-html.eml from the preceding example. Save the result as with-attachments.eml.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let email = CkoEmail()!
success = email.loadEml(mimePath: "text-and-html.eml")
if success != true {
print("\(email.lastErrorText!)")
return
}
let data = CkoBinData()!
success = data.appendString(str: "Time,Activity\r\n09:00,Welcome\r\n10:00,Field session\r\n", charset: "utf-8")
if success != true {
print("Failed: data.AppendString.")
return
}
success = email.addAttachmentBd(filename: "agenda.csv", binData: data, contentType: "text/csv")
if success != true {
print("\(email.lastErrorText!)")
return
}
// AddRelatedBd returns the identifier that must appear after cid: in the HTML.
let image = CkoBinData()!
success = image.appendEncoded(encData: "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAASUlEQVR4nGMQK/ImBv3//x/CYCBSNQkaIKqJ1YCmGkUDsigu1egakOWwqsaiAaICl2p0P8DV4VKNxdP4VWMPJTyqiY04sZGuAQBhyhp6A/ap2AAAAABJRU5ErkJggg==", encoding: "base64")
if success != true {
print("Failed: image.AppendEncoded.")
return
}
var cid: String? = email.addRelatedBd(filename: "confirmed.png", binData: image)
if email.lastMethodSuccess != true {
print("\(email.lastErrorText!)")
return
}
let html = CkoStringBuilder()!
html.append(value: "<p><img alt='Confirmed' src=\"cid:")
html.append(value: cid)
html.append(value: "\"></p>")
html.append(value: email.getHtmlBody())
success = email.addHtmlAlternativeBody(body: html.getAsString())
if success != true {
print("\(email.lastErrorText!)")
return
}
success = email.saveEml(path: "with-attachments.eml")
if success != true {
print("\(email.lastErrorText!)")
return
}
print("Saved with-attachments.eml.")
}