最近在做项目时,有一个需求就是将用户填写的feedback信息直接通过mail的形式发送给指定的receiver,在网上查阅了一下,可以使用skpsmtpmessage这个框架。
大家具体的可以参考这篇文章 https://www.jianshu.com/p/1c6b514e0777 ,我也是参考了这段代码,但发现并不能正常work,自己也是花了半天左右的时间去查找原因,我把它列出来,希望对大家有所帮助。
其它邮箱不知道,我用的是163邮箱
1, 对于163邮箱,首先需要开启“客户端授权密码”,这个需要用户手动设定的一个密码,用于第三方邮件客户端登录时认证使用,这个密码需要紧记,在后面代码会用到,这里假设 “客户端授权密码” 是 "Hello123".
-
紧接着开启SMTP服务并记下SMTP服务器(在后面代码会用到)"smtp.163.com"
下面就是关键代码了,我在网上看了许多代码,大多都差不多
-(void)sendButtonClicked:(UIBarButtonItem *)barButtonItem{
//1. Collect subject info
NSString *subjectInfo = self.subjectTf.text;
//2. Collect content info
NSString *contentTv = self.contentTv.text;
//3. send addr
NSString *sendAddr = @"sendaddr@163.com";
//4. receive addr
NSString *toAddr = @"receiveaddr@163.com";
SKPSMTPMessage *sendMessage = [[SKPSMTPMessage alloc]init];
sendMessage.fromEmail = sendAddr;
sendMessage.toEmail = toAddr;
/* Notice: 填好SMTP的服务器,第二步已经记录好了 */
sendMessage.relayHost = @"smtp.163.com";
sendMessage.requiresAuth = YES;
sendMessage.login = sendAddr;
/* Notice: 记住这里的密码并不是邮箱登录密码,而是授权密码,第一步已经说明了 */
sendMessage.pass = @"Hello123";
sendMessage.subject = subjectInfo;
sendMessage.wantsSecure = YES;
sendMessage.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,[NSString stringWithFormat:@"%@",contentTv]
,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
sendMessage.parts = [NSArray arrayWithObjects:plainPart, nil];
[sendMessage send];
}
- (void)messageSent:(SKPSMTPMessage *)message{
NSLog(@"messageSuccessed-----%@", message);
[self showPopUpWithTitle:@"提示信息" message:@"发送成功!"];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
NSLog(@"messageFailedToSend-----%@", message);
[self showPopUpWithTitle:@"提示信息" message:@"发送失败,请稍后再试!"];
}
- (void)showPopUpWithTitle:(NSString *)title message:(NSString *)msg{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self.navigationController popViewControllerAnimated:YES];
}]];
[self.navigationController presentViewController:alertController animated:YES completion:nil];
}
- 归纳与总结,代码其实都大同小异,也没什么可研究的,我就强调一下比较容易出错的两点(也是卡住我的地方)
(1) 才开始我用的密码是登录密码,所以mail怎么都不能发送成功,后来改用了授权密码后,就可以正常work了,授权密码是step1 提到了
sendMessage.pass = @"Hello123";
(2) 这里的smpt服务器不要填错了"smtp.163.com",详细见step2
sendMessage.relayHost = @"smtp.163.com";
5,然后就发送成功了
希望对大家有所帮助!