MailCore2是一个第三方的邮件SDK,支持POP和IMAP 方式接收邮件,以及smtp邮件发送
本篇应用:使用SMTP实现发送邮件的功能,以qq邮箱为例。
一,首先需要进入qq邮箱--设置--账户里开启SMTP服务
image.png
二,代码实现
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *sendMailButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 100, 150, 50)];
sendMailButton.backgroundColor = [UIColor blueColor];
[sendMailButton setTitle:@"send email" forState:UIControlStateNormal];
[sendMailButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sendMailButton addTarget:self action:@selector(sendEmail:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sendMailButton];
}
- (void)sendEmail:(UIButton *)button {
//1,创建MCOSMTPSession,配置好各个连接smtp邮箱的参数
MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];
smtpSession.username = @"xxxxxx";
smtpSession.password = @"授权码"; //是授权码,不是登录密码,
smtpSession.hostname = @"smtp.qq.com"; //SMTP服务器域名
smtpSession.port = 587; //端口
smtpSession.connectionType = MCOConnectionTypeStartTLS;
smtpSession.authType = MCOAuthTypeSASLPlain;
smtpSession.connectionLogger = ^(void *connectionID, MCOConnectionLogType type, NSData *data) {
if (data) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str:%@",str);
}
};
//2, 使用MCOMessageBuilder构建邮件体的发送内容
MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
//邮件头
[[builder header] setFrom:[MCOAddress addressWithDisplayName:@"just test" mailbox:@"xxxxxx@qq.com"]];
//设置邮件的接收人
NSString *toAddress = @"bbbbbb@qq.com";
MCOAddress *newAddress = [MCOAddress addressWithMailbox:toAddress];
[[builder header] setTo:@[newAddress]];
//设置邮件标题
[[builder header] setSubject:@"这是一封测试邮件,请忽略哈~"];
//设置邮件正文
[builder setTextBody:@"好久未联系,是否安好?"];
//3,将构建好的邮件发送出去
NSData *rfc822Data = [builder data];
MCOSMTPSendOperation *sendOperation = [smtpSession sendOperationWithData:rfc822Data];
[sendOperation start:^(NSError * _Nullable error) {
if (error) {
NSLog(@"邮件发送失败---%@",error);
} else {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"tips" message:@"邮件发送成功" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:alertAction];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
三,打开qq邮箱,在"已发送"列表里就能找到代码实现发送功能的邮件
image.png
注意:
1,不同邮箱其STMP服务器的hostName和port是不一样的,可自行百度查找,qq邮箱的如下
image.png
2,网上查找的很多例子里配置smtp的连接方式都是如下这种
smtpSession.connectionType = MCOConnectionTypeTLS;运行时总是报错:A stable connection to the server could not be established,发送失败。
将其改为 smtpSession.connectionType = MCOConnectionTypeStartTLS 就ok了。
原因我也不清楚,有大神知道的话烦请告之,在此谢过。