Sending Mailcore2 Plain Emails in Swift
Asked Answered
B

4

15

I've recently incorporated MailCore2 into my Objective-C project, and it has worked perfectly. Now, I am in the process of transitioning the code within the app to Swift. I have successfully imported the MailCore2 API into my swift project, but I see no documentation (Google search, libmailcore.com, github) on how to turn the following working Objective-C code into Swift Code:

MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];
smtpSession.hostname = @"smtp.gmail.com";
smtpSession.port = 465;
smtpSession.username = @"[email protected]";
smtpSession.password = @"password";
smtpSession.authType = MCOAuthTypeSASLPlain;
smtpSession.connectionType = MCOConnectionTypeTLS;

MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
MCOAddress *from = [MCOAddress addressWithDisplayName:@"Matt R"
                                              mailbox:@"[email protected]"];
MCOAddress *to = [MCOAddress addressWithDisplayName:nil 
                                            mailbox:@"[email protected]"];
[[builder header] setFrom:from];
[[builder header] setTo:@[to]];
[[builder header] setSubject:@"My message"];
[builder setHTMLBody:@"This is a test message!"];
NSData * rfc822Data = [builder data];

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

Does anyone know how to successfully send an email in Swift using this API? Thanks in advance to all who reply.

Benzedrine answered 17/7, 2015 at 22:0 Comment(0)
A
29

Here's how I did it:

Step 1) Import mailcore2, I'm using cocoapods

pod 'mailcore2-ios'

Step 2) Add mailcore2 to your bridging header: Project-Bridging-Header.h

#import <MailCore/MailCore.h>

Step 3) Translate to swift

var smtpSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.username = "[email protected]"
smtpSession.password = "xxxxxxxxxxxxxxxx"
smtpSession.port = 465
smtpSession.authType = MCOAuthType.SASLPlain
smtpSession.connectionType = MCOConnectionType.TLS
smtpSession.connectionLogger = {(connectionID, type, data) in
    if data != nil {
        if let string = NSString(data: data, encoding: NSUTF8StringEncoding){
            NSLog("Connectionlogger: \(string)")
        }
    }
}

var builder = MCOMessageBuilder()
builder.header.to = [MCOAddress(displayName: "Rool", mailbox: "[email protected]")]
builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "[email protected]")
builder.header.subject = "My message"
builder.htmlBody = "Yo Rool, this is a test message!"

let rfc822Data = builder.data()
let sendOperation = smtpSession.sendOperationWithData(rfc822Data)
sendOperation.start { (error) -> Void in
    if (error != nil) {
        NSLog("Error sending email: \(error)")
    } else {
        NSLog("Successfully sent email!")
    }
} 

Note You might be needing a special app password for your google account. See https://support.google.com/accounts/answer/185833

Alice answered 21/7, 2015 at 13:20 Comment(10)
@Rool Paap Have you done this with use_frameworks! flag in the Podfile instead of going with the bridging header way? I tried that but it gives me a No such module error when trying to import it like so import MailCore.Enwind
When I wrote this, I was still targeting iOS7. So I didn't use use_frameworks!. But let me see what I can do.Alice
Got the same 'No such module' error, couldn't find a solution. My cocoapods knowledge is limited. Sorry.Alice
Quick side note if you're using MailCore, sometimes gmail may prevent logging in, then you have to go to your gmail account and enable this setting.Enwind
@RoolPaap I used your code but I'm stilling get the error about credentials , you can see it in my question here please #36982676Pilotage
This works great. the question I have is in htmlBody. I am trying to put in the contents of textFields - one per line., how do I insert a line in the html body?Alva
I no longer use this Library to send mail, but previous versions of my app were approved.Alice
Top. This solutions is the fastest and the most reliable I found over the net :DXanthochroism
If for some reason this does not work for you then you can alternatively use other library skpsmtpmessage as explained here #28250601Christeenchristel
@RoolPaap is it possible to read emails from inbox in Swift app using MailCore from different providers like gmail, icloud etc?Valaria
B
7

For Swift 3 just copy this

    let smtpSession = MCOSMTPSession()
    smtpSession.hostname = "smtp.gmail.com"
    smtpSession.username = "[email protected]"
    smtpSession.password = "xxxxxxx"
    smtpSession.port = 465
    smtpSession.authType = MCOAuthType.saslPlain
    smtpSession.connectionType = MCOConnectionType.TLS
    smtpSession.connectionLogger = {(connectionID, type, data) in
        if data != nil {
            if let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
                NSLog("Connectionlogger: \(string)")
            }
        }
    }

    let builder = MCOMessageBuilder()
    builder.header.to = [MCOAddress(displayName: "Rool", mailbox: "[email protected]")]
    builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "[email protected]")
    builder.header.subject = "My message"
    builder.htmlBody = "Yo Rool, this is a test message!"

    let rfc822Data = builder.data()
    let sendOperation = smtpSession.sendOperation(with: rfc822Data!)
    sendOperation?.start { (error) -> Void in
        if (error != nil) {
            NSLog("Error sending email: \(error)")
        } else {
            NSLog("Successfully sent email!")
        }
    }
Batt answered 14/2, 2017 at 2:49 Comment(3)
Bro I am getting an Error saying "A stable connection could not be established" in the consoleRafaelarafaelia
@VenkateshChejarla, I am also getting same error. Error : Error sending email: Optional(Error Domain=MCOErrorDomain Code=1 "A stable connection to the server could not be established." UserInfo={NSLocalizedDescription=A stable connection to the server could not be established.})Oech
Does Anyone have solution for this error? #help me.Oech
O
4

To send an image as attachment in swift just add:

    var dataImage: NSData?
    dataImage = UIImageJPEGRepresentation(image, 0.6)!
    var attachment = MCOAttachment()
    attachment.mimeType =  "image/jpg"
    attachment.filename = "image.jpg"
    attachment.data = dataImage
    builder.addAttachment(attachment)
Outer answered 19/7, 2016 at 15:0 Comment(0)
M
0

I would've added this in the comments below the answer but there are so many.

The steps in the accepted answer worked especially using the link to the special app password for your google account.

But @RoolPaap used a different bridging header then the one I did. I used #include "Mailcore.h"

I followed this youtube video

#ifndef MyProjectName_Bridging_Header_h
#define MyProjectName_Bridging_Header_h

#include "Mailcore.h"

#endif /* MyProjectName_Bridging_Header_h */
Menado answered 2/3, 2019 at 3:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.