参照:iOS开发-发送邮件(E-mail)方法整理合集(共3种)
在iOS开发过程中,有时需要实现邮件发送的功能。发送邮件功能的实现大致可以分为三种方法:
- openURL(原生)——用户体检差,程序会进入后台,跳转至邮件发送界面。具体实现如下:
//创建可变的地址字符串对象
NSMutableString *mailUrl = [[NSMutableString alloc] init];
//添加收件人,如有多个收件人,可以使用componentsJoinedByString方法连接,连接符为","
NSString *recipients = @"sparkle_ds@163.com";
[mailUrl appendFormat:@"mailto:%@?", recipients];
//添加抄送人
NSString *ccRecipients = @"1622849369@qq.com";
[mailUrl appendFormat:@"&cc=%@", ccRecipients];
//添加密送人
NSString *bccRecipients = @"15690725786@163.com";
[mailUrl appendFormat:@"&bcc=%@", bccRecipients];
//添加邮件主题
[mailUrl appendFormat:@"&subject=%@",@"设置邮件主题"];
//添加邮件内容
[mailUrl appendString:@"&body=<b>Hello</b> World!"];
//跳转到系统邮件App发送邮件
NSString *emailPath = [mailUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:emailPath] options:@{} completionHandler:nil];
- MFMailComposeViewController(原生)——使用模态跳转出邮件发送界面。具体实现如下:
1) 项目需要导入MessageUI.framework框架
2) 在对应类里导入头文件:#import <MessageUI/MessageUI.h>
3) 对应的类遵从代理:MFMailComposeViewControllerDelegate
//判断用户是否已设置邮件账户
if ([MFMailComposeViewController canSendMail]) {
[self sendEmailAction]; // 调用发送邮件的代码
}else{
//给出提示,设备未开启邮件服务
}
-(void)sendEmailAction{
// 创建邮件发送界面
MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
// 设置邮件代理
[mailCompose setMailComposeDelegate:self];
// 设置收件人
[mailCompose setToRecipients:@[@"sparkle_ds@163.com"]];
// 设置抄送人
[mailCompose setCcRecipients:@[@"1622849369@qq.com"]];
// 设置密送人
[mailCompose setBccRecipients:@[@"15690725786@163.com"]];
// 设置邮件主题
[mailCompose setSubject:@"设置邮件主题"];
//设置邮件的正文内容
NSString *emailContent = @"我是邮件内容";
// 是否为HTML格式
[mailCompose setMessageBody:emailContent isHTML:NO];
// 如使用HTML格式,则为以下代码
// [mailCompose setMessageBody:@"<html><body><p>Hello</p><p>World!</p></body></html>" isHTML:YES];
//添加附件
UIImage *image = [UIImage imageNamed:@"qq"];
NSData *imageData = UIImagePNGRepresentation(image);
[mailCompose addAttachmentData:imageData mimeType:@"" fileName:@"qq.png"];
NSString *file = [[NSBundle mainBundle] pathForResource:@"EmptyPDF" ofType:@"pdf"];
NSData *pdf = [NSData dataWithContentsOfFile:file];
[mailCompose addAttachmentData:pdf mimeType:@"" fileName:@"EmptyPDF.pdf"];
// 弹出邮件发送视图
[_curVC presentViewController:mailCompose animated:YES completion:nil];
}
#pragma mark - MFMailComposeViewControllerDelegate的代理方法:
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
switch (result) {
case MFMailComposeResultCancelled:
NSLog(@"Mail send canceled: 用户取消编辑");
break;
case MFMailComposeResultSaved:
NSLog(@"Mail saved: 用户保存邮件");
break;
case MFMailComposeResultSent:
NSLog(@"Mail sent: 用户点击发送");
break;
case MFMailComposeResultFailed:
NSLog(@"Mail send errored: %@ : 用户尝试保存或发送邮件失败", [error localizedDescription]);
break;
}
// 关闭邮件发送视图
[_curVC dismissViewControllerAnimated:YES completion:nil];
}
-
SKPSMTPMessage(第三方库)——可以在不告知用户的情况下进行邮件发送,但建议在发送之前告知用户,让用户决定是否发送。具体实现如下:
1)添加该第三方库
2)项目还需要导入CFNetwork.framework框架
3)在对应类中导入头文件:#import "SKPSMTPMessage.h",#import "NSData+Base64Additions.h"
4)对应的类遵从代理:SKPSMTPMessageDelegate
//设置基本参数:
SKPSMTPMessage *mail = [[SKPSMTPMessage alloc] init];
[mail setSubject:@"设置邮件主题"]; // 设置邮件主题
[mail setToEmail:@"qq@qq.com"]; // 目标邮箱
[mail setFromEmail:@"myqq@qq.com"]; // 发送者邮箱
[mail setRelayHost:@"smtp.qq.com"]; // 发送邮件代理服务器
[mail setRequiresAuth:YES];
[mail setLogin:@"myqq@qq.com"]; // 发送者邮箱账号
[mail setPass:@"myqq_passwoed"]; // 发送者邮箱密码
[mail setWantsSecure:YES]; // 需要加密
[mail setDelegate:self];
//设置邮件正文内容:
NSString *content = [NSString stringWithCString:"测试内容" encoding:NSUTF8StringEncoding];
NSDictionary *plainPart = @{kSKPSMTPPartContentTypeKey : @"text/plain; charset=UTF-8", kSKPSMTPPartMessageKey : content, kSKPSMTPPartContentTransferEncodingKey : @"8bit"};
//添加附件(以下代码可在SKPSMTPMessage库的DMEO里找到):
NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@"EmptyPDF" ofType:@"pdf"];
NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"EmptyPDF.pdf\"",kSKPSMTPPartContentTypeKey, @"attachment;\r\n\tfilename=\"EmptyPDF.pdf\"",kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
//执行发送邮件代码
[mail setParts:@[plainPart, vcfPart]]; // 邮件首部字段、邮件内容格式和传输编码
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[mail send];
});
//SKPSMTPMessage代理,可以获知成功/失败进行后续步骤处理
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(@"%@", message);
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
NSLog(@"message - %@\nerror - %@", message, error);
}
(但我这里一直提示:Attempting to connect to server at: smtp.exmail.qq.com:25,我想是因为代理服务器设置的不对,望各位看官不吝赐教)
期待你的评论建议O(∩_∩)O~