Skip to content
Hoà V. DINH edited this page Aug 9, 2016 · 7 revisions

Basic SMTP Usage

In order to send a message using MailCore 2, we first have to compose that message using MCOMessageBuilder, then we can hand it off to an asynchronous operation generated by out SMTP session to deliver that message to the SMTP server. Here's a quick example, assuming you have arrays of email addresses for to/cc/bcc:

MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];
smtpSession.hostname = @"smtp.gmail.com";
smtpSession.port = 465;
smtpSession.username = USERNAME;
smtpSession.password = PASSWORD;
smtpSession.connectionType = MCOConnectionTypeTLS;

MCOMessageBuilder * builder = [[MCOMessageBuilder alloc] init];
[[builder header] setFrom:[MCOAddress addressWithDisplayName:nil mailbox:USERNAME]];
NSMutableArray *to = [[NSMutableArray alloc] init];
for(NSString *toAddress in RECIPIENTS) {
    MCOAddress *newAddress = [MCOAddress addressWithMailbox:toAddress];
    [to addObject:newAddress];
}
[[builder header] setTo:to];
NSMutableArray *cc = [[NSMutableArray alloc] init];
for(NSString *ccAddress in CC) {
    MCOAddress *newAddress = [MCOAddress addressWithMailbox:ccAddress];
    [cc addObject:newAddress];
}
[[builder header] setCc:cc];
NSMutableArray *bcc = [[NSMutableArray alloc] init];
for(NSString *bccAddress in BCC) {
    MCOAddress *newAddress = [MCOAddress addressWithMailbox:bccAddress];
    [bcc addObject:newAddress];
}
[[builder header] setBcc:bcc];
[[builder header] setSubject:SUBJECT];
[builder setHTMLBody:BODY];
NSData * rfc822Data = [builder data];

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

 // if you're running in a command line tool.
// [[NSRunLoop currentRunLoop] run];

So as you can see, we compose the message, then put our callback code inside of the start block.

Clone this wiki locally