在IOS开发中,有时候我们会需要用到邮件发送的功能。比如,接收用户反馈和程序崩溃通知等等。其实这个功能是很常用的,因为我目前就有发送邮件的开发需求,所以顺便整理下IOS发送邮件的方法。
IOS原生自带有两种方法发送邮件的方法,另一种是使用第三方库:
1)openURL(原生)
——用户体验较差,程序会进入后台,跳转至邮件发送界面。
2)MFMailComposeViewController(原生)
——不会进入后台,使用模态弹出邮件发送视图。
3)SKPSMTPMessage( https://github.com/jetseven/skpsmtpmessage )
——你可以不需要告知用户将要进行邮件发送的事情,我在想这个是不是不符合苹果的理论。当然你也可以在发送之前弄个弹出框告知用户,并让用户选择是否发送。
以下代码均在真机(IOS8.0)进行测试,并通过测试。
一、使用openURL发送邮件:
创建可变的地址字符串对象:
NSMutableString *mailUrl = [[NSMutableString alloc] init];
添加收件人:
NSArray *toRecipients = @[@"写你们自己的邮箱测试@qq.com"];
// 注意:如有多个收件人,可以使用componentsJoinedByString方法连接,连接符为@","
[mailUrl appendFormat:@"mailto:%@", toRecipients[0]];
添加抄送人:
NSArray *ccRecipients = @[@"1229436624@qq.com"];
[mailUrl appendFormat:@"?cc=%@", ccRecipients[0]];
添加密送人:
NSArray *bccRecipients = @[@"shana_happy@126.com"];
[mailUrl appendFormat:@"&bcc=%@", bccRecipients[0]];
添加邮件主题和邮件内容:
[mailUrl appendString:@"&subject=my email"];
[mailUrl appendString:@"&body=<b>Hello</b> World!"];
效果图:
二、使用MFMailComposeViewController发送邮件
使用前注意:
1)项目需要导入框架:MessageUI.framework
2)使用的Controlelr里导入头文件:#import <MessageUI/MessageUI.h>
获取用户是否设置了邮件账户:
if ([MFMailComposeViewController canSendMail]) { // 用户已设置邮件账户
[self sendEmailAction]; // 调用发送邮件的代码
}
sendEmailAction方法代码:
- (void)sendEmailAction
{
// 邮件服务器
MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
// 设置邮件代理
[mailCompose setMailComposeDelegate:self];
// 设置邮件主题
[mailCompose setSubject:@"我是邮件主题"];
// 设置收件人
[mailCompose setToRecipients:@[@"1147626297@qq.com"]];
// 设置抄送人
[mailCompose setCcRecipients:@[@"1229436624@qq.com"]];
// 设置密抄送
[mailCompose setBccRecipients:@[@"shana_happy@126.com"]];
/**
* 设置邮件的正文内容
*/
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:@"image"];
NSData *imageData = UIImagePNGRepresentation(image);
[mailCompose addAttachmentData:imageData mimeType:@"" fileName:@"custom.png"];
NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"];
NSData *pdf = [NSData dataWithContentsOfFile:file];
[mailCompose addAttachmentData:pdf mimeType:@"" fileName:@"7天精通IOS233333"];
// 弹出邮件发送视图
[self presentViewController:mailCompose animated:YES completion:nil];
}
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;
}
// 关闭邮件发送视图
[self dismissViewControllerAnimated:YES completion:nil];
}
程序运行效果图:
在IOS的邮件发送里,附件会直接显示在正文的下方,但是不要误认为是图片放在了正文当中,两者是有区别的!
三、 使用第三方库SKPSMTPMessage发送邮件
使用前注意:
1)下载第三方库(下载地址文章开头)
2)导入类#import "SKPSMTPMessage.h"、#import "NSData+Base64Additions.h"
设置基本参数:
SKPSMTPMessage *mail = [[SKPSMTPMessage alloc] init];
[mail setSubject:@"我是主题"]; // 设置邮件主题
[mail setToEmail:@"填你们自己的@qq.com"]; // 目标邮箱
[mail setFromEmail:@"填你们自己的@qq.com"]; // 发送者邮箱
[mail setRelayHost:@"smtp.qq.com"]; // 发送邮件代理服务器
[mail setRequiresAuth:YES];
[mail setLogin:@"填你们自己的@qq.com"]; // 发送者邮箱账号
[mail setPass:@"填你们自己的"]; // 发送者邮箱密码
[mail setWantsSecure:YES]; // 需要加密
[mail setDelegate:self];
设置邮件正文内容:
NSString *content = [NSString stringWithCString:"测试内容" encoding:NSUTF8StringEncoding];
NSDictionary *plainPart = @{kSKPSMTPPartContentTypeKey : @"text/plain", kSKPSMTPPartMessageKey : content, kSKPSMTPPartContentTransferEncodingKey : @"8bit"};
添加附件(以下代码可在SKPSMTPMessage库的DMEO里找到):
NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"vcf"];
NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"test.vcf\"",kSKPSMTPPartContentTypeKey,
@"attachment;\r\n\tfilename=\"test.vcf\"",kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
执行发送邮件代码:
[mail setParts:@[plainPart, vcfPart]]; // 邮件首部字段、邮件内容格式和传输编码
[mail send];
SKPSMTPMessage代理,可以获知成功/失败进行后续步骤处理:
- (void)messageSent:(SKPSMTPMessage *)message
{
NSLog(@"%@", message);
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
NSLog(@"message - %@\nerror - %@", message, error);
}
效果图:
什么效果图?没有效果图,只因任性。
这里采取的是不通知用户发送邮件,所以没效果图。
小结:本来第三方库那个我是不想写出来的,因为总感觉不安全,不要问我为什么,男人的直觉?其实是代码太难看懂了,可能是我技术太菜了。
本篇文章借鉴了:
http://blog.sina.com.cn/s/blog_7d280d7c0101da7d.html
http://www.cnblogs.com/zhuqil/archive/2011/07/21/2112816.html
http://blog.csdn.net/zhibudefeng/article/details/7677421
说法二
1.openURL
- #pragma mark - 使用系统邮件客户端发送邮件
- -(void)launchMailApp
- {
- NSMutableString *mailUrl = [[[NSMutableString alloc]init]autorelease];
- //添加收件人
- NSArray *toRecipients = [NSArray arrayWithObject: @"first@example.com"];
- [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]];
- //添加抄送
- NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
- [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]];
- //添加密送
- NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
- [mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]];
- //添加主题
- [mailUrl appendString:@"&subject=my email"];
- //添加邮件内容
- [mailUrl appendString:@"&body=<b>email</b> body!"];
- NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
- [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
- }
2.MFMailComposeViewController
- 1.项目中引入MessageUI.framework;
- 2.在使用的文件中导入MFMailComposeViewController.h头文件;
- 3.实现MFMailComposeViewControllerDelegate,处理邮件发送事件;
- 4.调出邮件发送窗口前先使用MFMailComposeViewController里的“+ (BOOL)canSendMail”方法检查用户是否设置了邮件账户;
- 5.初始化MFMailComposeViewController,构造邮件体
- //
- // ViewController.h
- // MailDemo
- //
- // Created by LUOYL on 12-4-4.
- // Copyright (c) 2012年 http://luoyl.info. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- #import <MessageUI/MFMailComposeViewController.h>
- @interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>
- @end
- #pragma mark - 在应用内发送邮件
- //激活邮件功能
- - (void)sendMailInApp
- {
- Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
- if (!mailClass) {
- [self alertWithMessage:@"当前系统版本不支持应用内发送邮件功能,您可以使用mailto方法代替"];
- return;
- }
- if (![mailClass canSendMail]) {
- [self alertWithMessage:@"用户没有设置邮件账户"];
- return;
- }
- [self displayMailPicker];
- }
- //调出邮件发送窗口
- - (void)displayMailPicker
- {
- MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
- mailPicker.mailComposeDelegate = self;
- //设置主题
- [mailPicker setSubject: @"eMail主题"];
- //添加收件人
- NSArray *toRecipients = [NSArray arrayWithObject: @"first@example.com"];
- [mailPicker setToRecipients: toRecipients];
- //添加抄送
- NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
- [mailPicker setCcRecipients:ccRecipients];
- //添加密送
- NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
- [mailPicker setBccRecipients:bccRecipients];
- // 添加一张图片
- UIImage *addPic = [UIImage imageNamed: @"Icon@2x.png"];
- NSData *imageData = UIImagePNGRepresentation(addPic); // png
- //关于mimeType:http://www.iana.org/assignments/media-types/index.html
- [mailPicker addAttachmentData: imageData mimeType: @"" fileName: @"Icon.png"];
- //添加一个pdf附件
- NSString *file = [self fullBundlePathFromRelativePath:@"高质量C++编程指南.pdf"];
- NSData *pdf = [NSData dataWithContentsOfFile:file];
- [mailPicker addAttachmentData: pdf mimeType: @"" fileName: @"高质量C++编程指南.pdf"];
- NSString *emailBody = @"<font color='red'>eMail</font> 正文";
- [mailPicker setMessageBody:emailBody isHTML:YES];
- [self presentModalViewController: mailPicker animated:YES];
- [mailPicker release];
- }
- #pragma mark - 实现 MFMailComposeViewControllerDelegate
- - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
- {
- //关闭邮件发送窗口
- [self dismissModalViewControllerAnimated:YES];
- NSString *msg;
- switch (result) {
- case MFMailComposeResultCancelled:
- msg = @"用户取消编辑邮件";
- break;
- case MFMailComposeResultSaved:
- msg = @"用户成功保存邮件";
- break;
- case MFMailComposeResultSent:
- msg = @"用户点击发送,将邮件放到队列中,还没发送";
- break;
- case MFMailComposeResultFailed:
- msg = @"用户试图保存或者发送邮件失败";
- break;
- default:
- msg = @"";
- break;
- }
- [self alertWithMessage:msg];
- }