參照:iOS開(kāi)發(fā)-發(fā)送郵件(E-mail)方法整理合集(共3種)
在iOS開(kāi)發(fā)過(guò)程中赶促,有時(shí)需要實(shí)現(xiàn)郵件發(fā)送的功能沉御。發(fā)送郵件功能的實(shí)現(xiàn)大致可以分為三種方法:
- openURL(原生)——用戶(hù)體檢差橘霎,程序會(huì)進(jìn)入后臺(tái)赁酝,跳轉(zhuǎn)至郵件發(fā)送界面谣膳。具體實(shí)現(xiàn)如下:
//創(chuàng)建可變的地址字符串對(duì)象
NSMutableString *mailUrl = [[NSMutableString alloc] init];
//添加收件人,如有多個(gè)收件人谈山,可以使用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=%@",@"設(shè)置郵件主題"];
//添加郵件內(nèi)容
[mailUrl appendString:@"&body=<b>Hello</b> World!"];
//跳轉(zhuǎn)到系統(tǒng)郵件App發(fā)送郵件
NSString *emailPath = [mailUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:emailPath] options:@{} completionHandler:nil];
- MFMailComposeViewController(原生)——使用模態(tài)跳轉(zhuǎn)出郵件發(fā)送界面忆某。具體實(shí)現(xiàn)如下:
1) 項(xiàng)目需要導(dǎo)入MessageUI.framework框架
2) 在對(duì)應(yīng)類(lèi)里導(dǎo)入頭文件:#import <MessageUI/MessageUI.h>
3) 對(duì)應(yīng)的類(lèi)遵從代理:MFMailComposeViewControllerDelegate
//判斷用戶(hù)是否已設(shè)置郵件賬戶(hù)
if ([MFMailComposeViewController canSendMail]) {
[self sendEmailAction]; // 調(diào)用發(fā)送郵件的代碼
}else{
//給出提示,設(shè)備未開(kāi)啟郵件服務(wù)
}
-(void)sendEmailAction{
// 創(chuàng)建郵件發(fā)送界面
MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
// 設(shè)置郵件代理
[mailCompose setMailComposeDelegate:self];
// 設(shè)置收件人
[mailCompose setToRecipients:@[@"sparkle_ds@163.com"]];
// 設(shè)置抄送人
[mailCompose setCcRecipients:@[@"1622849369@qq.com"]];
// 設(shè)置密送人
[mailCompose setBccRecipients:@[@"15690725786@163.com"]];
// 設(shè)置郵件主題
[mailCompose setSubject:@"設(shè)置郵件主題"];
//設(shè)置郵件的正文內(nèi)容
NSString *emailContent = @"我是郵件內(nèi)容";
// 是否為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"];
// 彈出郵件發(fā)送視圖
[_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: 用戶(hù)取消編輯");
break;
case MFMailComposeResultSaved:
NSLog(@"Mail saved: 用戶(hù)保存郵件");
break;
case MFMailComposeResultSent:
NSLog(@"Mail sent: 用戶(hù)點(diǎn)擊發(fā)送");
break;
case MFMailComposeResultFailed:
NSLog(@"Mail send errored: %@ : 用戶(hù)嘗試保存或發(fā)送郵件失敗", [error localizedDescription]);
break;
}
// 關(guān)閉郵件發(fā)送視圖
[_curVC dismissViewControllerAnimated:YES completion:nil];
}
-
SKPSMTPMessage(第三方庫(kù))——可以在不告知用戶(hù)的情況下進(jìn)行郵件發(fā)送弃舒,但建議在發(fā)送之前告知用戶(hù),讓用戶(hù)決定是否發(fā)送状原。具體實(shí)現(xiàn)如下:
1)添加該第三方庫(kù)
2)項(xiàng)目還需要導(dǎo)入CFNetwork.framework框架
3)在對(duì)應(yīng)類(lèi)中導(dǎo)入頭文件:#import "SKPSMTPMessage.h"聋呢,#import "NSData+Base64Additions.h"
4)對(duì)應(yīng)的類(lèi)遵從代理:SKPSMTPMessageDelegate
//設(shè)置基本參數(shù):
SKPSMTPMessage *mail = [[SKPSMTPMessage alloc] init];
[mail setSubject:@"設(shè)置郵件主題"]; // 設(shè)置郵件主題
[mail setToEmail:@"qq@qq.com"]; // 目標(biāo)郵箱
[mail setFromEmail:@"myqq@qq.com"]; // 發(fā)送者郵箱
[mail setRelayHost:@"smtp.qq.com"]; // 發(fā)送郵件代理服務(wù)器
[mail setRequiresAuth:YES];
[mail setLogin:@"myqq@qq.com"]; // 發(fā)送者郵箱賬號(hào)
[mail setPass:@"myqq_passwoed"]; // 發(fā)送者郵箱密碼
[mail setWantsSecure:YES]; // 需要加密
[mail setDelegate:self];
//設(shè)置郵件正文內(nèi)容:
NSString *content = [NSString stringWithCString:"測(cè)試內(nèi)容" encoding:NSUTF8StringEncoding];
NSDictionary *plainPart = @{kSKPSMTPPartContentTypeKey : @"text/plain; charset=UTF-8", kSKPSMTPPartMessageKey : content, kSKPSMTPPartContentTransferEncodingKey : @"8bit"};
//添加附件(以下代碼可在SKPSMTPMessage庫(kù)的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];
//執(zhí)行發(fā)送郵件代碼
[mail setParts:@[plainPart, vcfPart]]; // 郵件首部字段、郵件內(nèi)容格式和傳輸編碼
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[mail send];
});
//SKPSMTPMessage代理颠区,可以獲知成功/失敗進(jìn)行后續(xù)步驟處理
-(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削锰,我想是因?yàn)榇矸?wù)器設(shè)置的不對(duì),望各位看官不吝賜教)
期待你的評(píng)論建議O(∩_∩)O~