2015-07-17 8 views
9

Недавно я включил MailCore2 в свой проект Objective-C, и он отлично работал. Теперь я в процессе перехода кода в приложение к Swift. Я успешно импортирован API MailCore2 в мой стремительный проект, но я не вижу никакой документации (поиска Google, libmailcore.com, GitHub) о том, как включить следующий код рабочего Objective-C в Swift код:Отправка почтовых писем Mailcore2 в Swift

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!"); 
    } 
}]; 

Значит ли кто-нибудь знает, как успешно отправить письмо в Swift с помощью этого API? Заранее благодарю всех, кто отвечает.

ответ

22

Вот как я это сделал:

Шаг 1) Импорт mailcore2, я использую cocoapods

pod 'mailcore2-ios' 

Шаг 2) Добавить mailcore2 в свой мостиковых заголовок: Project-Bridging- header.h

#import <MailCore/MailCore.h> 

Шаг 3) Тр anslate к быстрому

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!") 
    } 
} 

Примечание Вы можете быть необходимости специального приложения пароль для учетной записи Google. См https://support.google.com/accounts/answer/185833

+0

Спасибо так много! Код работал отлично! – iProgramIt

+0

@Rool Paap Вы сделали это с флагом 'use_frameworks!' В 'Podfile' вместо того, чтобы идти с мостом для заголовка? Я пробовал это, но это дает мне ** Нет такой ошибки модуля ** при попытке импортировать ее так, как «import MailCore». – Isuru

+0

Когда я написал это, я все еще нацелился на iOS7. Поэтому я не использовал use_frameworks !. Но позвольте мне посмотреть, что я могу сделать. –

3

Чтобы отправить изображение как вложение в стрижа только добавить:

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) 
6

Для Swift 3 просто скопировать этот

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!") 
     } 
    } 
Смежные вопросы