How to send an email without using MailComposeViewController?

Vu Tran
2 min readMar 14, 2020

--

In a freelance project, my client wants to send an email to confirm what user books on their app after filling in the application form. The email will be sent to the user’s mailbox based on the brief information provided. They required to send in silence. It means the application will automatically send the email without presenting an MFMailComposeViewController or other mail UI.

After researching I found MailCore2, provides a simple and asynchronous Objective-C API to with the email protocols IMAP, POP, and SMTP. All source code is written in Objective-C, you should read README to implement it correctly.

  1. Initialize SMTP Section.
MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];
smtpSession.hostname = @"smtp.gmail.com";
smtpSession.port = 465;
smtpSession.username = RR_Email;
smtpSession.password = RR_Pass;
smtpSession.authType = MCOAuthTypeSASLPlain;
smtpSession.connectionType = MCOConnectionTypeTLS;

2. Initialize Message Builder. It contains all information, for example, title, subject, attached file…

MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
MCOAddress *from = [MCOAddress addressWithDisplayName:@"title"
mailbox:RR_Email];
MCOAddress *to = [MCOAddress addressWithDisplayName:nil
mailbox:toEmail];
[[builder header] setFrom:from];
[[builder header] setTo:@[to]];
[[builder header] setSubject:@"Title"];
[builder setTextBody:@"Content"];
// add the attached file
NSData *vcfData = ...
[builder addAttachment:[MCOAttachment attachmentWithData:vcfData filename:@"filename"]];

3. Send an email and handle all the responses

MCOSMTPSendOperation *sendOperation = [smtpSession sendOperationWithData:[builder data]];[sendOperation start:^(NSError *error) {
if(error) {
NSLog(@"Error sending email: %@", error);
} else {
NSLog(@"Successfully sent email!");
}
}];

Yeah! That’s all.

For projects, the client wants to custom mail UI or builds feedback UI, you may also use this framework. After build custom UI, you implement send-email-in-background, noted above.

Happy coding!

In the Swift project, you need a bridging header file to use MailCore2, a guide from Charles Xavier.

You can also try others and choose one which is suitable for you.

--

--