一尘不染

在Swift中发送Mailcore2纯电子邮件

swift

我最近将MailCore2合并到我的Objective-
C项目中,并且运行良好。现在,我正在将应用程序中的代码转换为Swift。我已经成功地将MailCore2
API导入了我的swift项目,但是我看不到任何文档(Google搜索,libmailcore.com,github)如何将以下工作的Objective-
C代码转换为Swift代码:

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

MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
MCOAddress *from = [MCOAddress addressWithDisplayName:@"Matt R"
                                              mailbox:@"matt@gmail.com"];
MCOAddress *to = [MCOAddress addressWithDisplayName:nil 
                                            mailbox:@"hoa@gmail.com"];
[[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!");
    }
}];

有谁知道如何使用此API在Swift中成功发送电子邮件?在此先感谢所有答复。


阅读 361

收藏
2020-07-07

共1个答案

一尘不染

这是我的做法:

步骤1) 导入mailcore2,我正在使用cocoapods

pod 'mailcore2-ios'

步骤2) 将mailcore2添加到您的桥接头中:Project-Bridging-Header.h

#import <MailCore/MailCore.h>

步骤3) 转换为快速

var smtpSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.username = "matt@gmail.com"
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: "itsrool@gmail.com")]
builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "matt@gmail.com")
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

2020-07-07