- Newest
- Most votes
- Most comments
After a lot of reading, I finally get it working. You need to write a big string, based on MIME-Standards. This big string you have to encode to BASE64. Attachments needed also to transform from data to an BASE64-String.
I will post my code, which can send Mails with an .png image. I will test other fileTypes as well, but it have to be the same principle.
First I created a enum for my fileTypes.
enum DataTypes{
case png
case jpg
case pdf
}
Now I created a function to get the string-value for the specific DataType
func getMIMEDataType(dataType:DataTypes) -> String{
var MIMEData = String()
switch dataType {
case .png:
MIMEData = "image/png"
case .jpg:
MIMEData = "image/jpg"
case .pdf:
MIMEData = "application/pdf"
}
return MIMEData
}
Finally the function to send the raw-mail. There are already variables in the message-string so you can use this function flexible.
func sendRawMail(sender:String,reciepients:[String],subject:String,message:String,attachment:Data?,dataType:DataTypes?,attachmentName:String?,completion: @escaping (_ messageCode:String?,_ error:Error?) -> ()){
let attachmentString = attachment!.base64EncodedString(options: .lineLength64Characters)
let MIMEDataType = getMIMEDataType(dataType: dataType!)
let message:String = """
Subject: \(subject)
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="XXXXboundary text"
This is a multipart message in MIME format.
--XXXXboundary text
Content-Type: text/plain
\(message)
--XXXXboundary text
Content-Type: \(MIMEDataType);
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="\(attachmentName!).\(MIMEDataType.components(separatedBy: "/")[1])"
\(attachmentString)
--XXXXboundary text--
"""
let data = message.data(using: .utf8)
let rawMessage = AWSSESRawMessage()
rawMessage?.data = data
let rawRequest = AWSSESSendRawEmailRequest()
rawRequest?.destinations = reciepients
rawRequest?.source = sender
rawRequest?.rawMessage = rawMessage
AWSSES.default().sendRawEmail(rawRequest!) { (response, error) in
if let response = response{
completion(response.messageId,nil)
}
if let error = error{
completion(nil,error)
}
}
}
usage:
sendRawMail(sender: "sender.mail@mail.com", reciepients: ["recipient.mail@mail.com"], subject: "This is a test", message: "TestMessage", attachment: attachment.data, dataType: .png, attachmentName: "testpicture") { (messageID, error) in
if let messageID = messageID{
print(messageID)
}
if let error = error{
print(error)
}
hope it will help somebody in future :)
Hi ChrisSTMS,
I'm glad you were able to get it working. I was just researching this myself, and not having much luck. I definitely appreciate you posting the solution for other users to find. Thank you!
Brent @ AWS
Relevant content
- asked 5 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated a year ago