Intro to tutorial on how to send email with attachment in swift
In this tutorial, we are going to learn how to send email with attachment from our iOS app which we will made using swift language. We are using xcode version 10 for this tutorial. So please follow below steps to learn how to send email with attachment in swift programmatically.
Steps to send email with attachment in swift
1: Create a single view application template project in xcode and name it “SendMailAttachment“
2: Open “Main,storyboard” file and first change background color for the view and drag a UIButton on to the view. Set title for the button “Send Email“. Set the font and color as per your requirement or how you like it would appear in your app.
3: Open “ViewController.swift” and create an IBAction for the button we created in step 2.
Open “Main,storyboard” file and connect IBAction created in step 3 to “touchUpInside” event of UIButton.
5: Now, as we set up our UI and now it’s time to do some coding. So open “ViewController.swift“. In order to send email first we need to import MessageUI framework.
Inside the IBAction, paste below code
In the above code, first we checked whether an email account is configured in iPhone settings app using “canSendMail
” function of “MFMailComposeViewController” class, as if it’s not configured then we will not able to send email thus we print message for same in console. If mail is configured then, we created an object of “MFMailComposeViewController” class and set subject for email, message and recipients. All these options are optional and you can leave them blank too. Finally we will present email composer to the user.
Now, at this point, we are presenting the composer screen but the question arises how can we get notified whether user sent the email or canceled it or saved to drafts. To solve this problem, we use delegate provided by “MFMailComposeViewController”. Below is the complete code for the same and is self explanatory.
Adding attachment to email using addAttachmentData of
For sending attachment, first we will add a pdf file to our project. Then, we get the file path and make a data object of that file. Finally we will use “addAttachmentData” property of mail composer
to add the attachment. Below is the complete code adding attachment to our mail composer or in short our email.
Where to go from here
In this tutorial, we learned about how to send attachment with email in our ios app using swift. We leaned how to add attachment to email composer in iOS SDK. Download source code form here