Platform
Docs
Solutions
ContactLog In

2 Ways to Send Emails with Swift [Step-by-Step Tutorial]

  • Introduction
  • MessageUI
  • MailSlurp
  • Conclusion

Email sending has become a common feature in modern web and mobile applications since it is a great way to communicate with end users. So, it is essential to understand how to implement these common features in multiple languages to deliver the best for your customers. So, in this article, I will discuss how to implement an email-sending feature with Swift.

Swift is a powerful programming language developed by Apple. It is also much simpler to understand and write than other languages. This article mainly focused on two main options for sending an email with Swift: MessageUI framework and MailSlurp.

Let's go through the benefits and drawbacks followed by step-by-step tutorial for each option.

1. Using MessageUI framework

MessageUI is a framework provided by Apple to implement user interfaces for composing email and text messages. It provides specialized view controllers for displaying the standard composition interfaces for email and text messages. MessageUI enhances the email-sending capabilities of your application since users do not need to leave the application to send and edit emails.

Advantages of using MessageUI

  • Easy to implement.
  • It works on every iOS device.
  • Fully open source.

Drawbacks of using MessageUI

  • Limited only to the iOS platform.
  • Lack of support for earlier iOS versions.
  • Incomplete cross-platform support.

Tutorial: How to send emails using the MessageUI framework in Swift

Step 1 - Import the MessageUI framework

First, Import the MessageUI framework t your project. It provides the MFMailComposeViewController class that controls how the email composer is displayed within the application.

1 import MessageUI

Step 2 - Set up a button

Copy the following code and set up a button. It will add a button to your view controller.

1 let mailButton = UIButton()

After that, call the below function inside the ViewDidLoad.

1 2 3 4 5 6 7 8 9 10 11 12 13 func setupButton() { view.addSubview(mailButton) mailButton.backgroundColor = .systemBlue mailButton.addTarget(self, action: #selector(showMailComposer), for: .touchUpInside) mailButton.setTitle(NSLocalizedString("Email me", comment: ""), for: .normal) mailButton.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium) mailButton.translatesAutoresizingMaskIntoConstraints = false mailButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true mailButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true mailButton.heightAnchor.constraint(equalToConstant: 50).isActive = true mailButton.widthAnchor.constraint(equalToConstant: 300).isActive = true }

Step 3 - Add the MFMailComposeViewControllerDelegate method

Update your view controller with MFMailComposeViewControllerDelegate. It allows you to call the mail ViewController delegate directly from your application without creating a custom email composer.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 extension ViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if let _ = error { controller.dismiss(animated: true, completion: nil) return } switch result { case .cancelled: break case .failed: break case .saved: break case .sent: break } controller.dismiss(animated: true, completion: nil) } }

Step 4 - Sending the email

Copy and paste the following code into the view controller to give the button action. It sets the sender, the subject, and the body. In addition, you can add attachments using the .addAttachmentData() method.

1 2 3 4 5 6 7 8 9 10 11 @objc func showMailComposer() { guard MFMailComposeViewController.canSendMail() else { return } let composer = MFMailComposeViewController() composer.mailComposeDelegate = self composer.setToRecipients(["receiver@gmail.com"]) composer.setSubject("Hey there!") composer.setMessageBody("This is my first email", isHTML: false) present(composer, animated: true) }

The finalized code for your ViewController will look like the below:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 import UIKit import MessageUI class ViewController: UIViewController { let mailButton = UIButton() override func viewDidLoad() { super.viewDidLoad() setupButton() } func setupButton() { view.addSubview(mailButton) mailButton.backgroundColor = .systemBlue mailButton.addTarget(self, action: #selector(showMailComposer), for: .touchUpInside) mailButton.setTitle(NSLocalizedString("Email me", comment: ""), for: .normal) mailButton.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium) mailButton.translatesAutoresizingMaskIntoConstraints = false mailButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true mailButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true mailButton.heightAnchor.constraint(equalToConstant: 50).isActive = true mailButton.widthAnchor.constraint(equalToConstant: 300).isActive = true } @objc func showMailComposer() { guard MFMailComposeViewController.canSendMail() else { return } let composer = MFMailComposeViewController() composer.mailComposeDelegate = self composer.setToRecipients(["receiver@gmail.com"]) composer.setSubject("Hey there!") composer.setMessageBody("This is my first email", isHTML: false) present(composer, animated: true) } } extension ViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if let _ = error { controller.dismiss(animated: true, completion: nil) return } switch result { case .cancelled: break case .failed: break case .saved: break case .sent: break } controller.dismiss(animated: true, completion: nil) } }

2. Using MailSlurp

MailSlurp is a powerful API service that allows you to test and develop email and messaging features. It supports various languages and protocols programming languages, including Swift, NodeJS, PHP, Ruby, GraphQL, SMTP, C#, Java, and more. It provides comprehensive documentation for all languages, and you can easily get started by creating a MailSlrup account.

Advantages of using MailSlurp

  • Provide testing email functionality.
  • Open source tool.
  • It supports any programming language.
  • Good documentation.

Drawbacks of using MailSlurp

  • A subscription is required to use all features.

Tutorial: How to send emails using MailSlurp in Swift

The MailSlurp library gives every endpoint on the MailSlurp REST API a controller.

Step 1 - Install MailSlurp into Swift

Use Package.swift and Swift Package Manager to install MailSlurp

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // swift-tools-version:5.3 import PackageDescription let package = Package( name: "example", // add platform as mailslurp requires macOS >= v10_11 platforms: [ .macOS(.v10_11) ], dependencies: [ // add mailslurp dependency .package(URL: "https://github.com/mailslurp/mailslurp-client-swift", from: "12.4.2"), ], targets: [ // add mailslurp to the target .target( name: "my-project", dependencies: ["mailslurp"]), .testTarget( name: "my-project-test", dependencies: ["mailslurp"]), ] )

Then, run swift package resolve command to install dependencies.

Step 2 - Setup API Key

You can use the free version of MailSlrup for personal use. But you need an API key to make requests. For that, sign up with MailSlrup and create an API Key using the MailSlurp dashboard.

Step 3 - Using MailSlurp in Swift

Then, you can build a simple email request using the APi key like below:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 CommonActionsControllerAPI.sendEmailSimpleWithRequestBuilder(emailOptions: sendOptions) .addHeader(name: "x-api-key", value: apiKey) .execute() .done { response in // handle success } .catch(policy: .allErrors) { err in // handle error guard let e = err as? mailslurp.ErrorResponse else { error = err.localizedDescription return } switch e { case .error(let statusCode, let data, _, _): let msg = String(decoding: data!, as: UTF8.self) error = "\(statusCode) Bad request: \(msg)" } }

Conclusion

This article discussed two methods we can use to implement email sending with Swift applications, alongside their pros and cons. I hope these suggestions will help you to easily implement an email-sending service for your Swift applications.

View More Guides

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Platform

Users

Content

Channels

Sending

Workflows

Preferences

Inbox

Workspaces

Observability

API Status

Changelog

© 2024 Courier. All rights reserved.