pod接入方式:
pod 'skpsmtpmessage','~> 0.0.1'
#import "ViewController.h"
#import <SKPSMTPMessage.h>
#import <NSData+Base64Additions.h>
@interface ViewController ()<SKPSMTPMessageDelegate>
@property (nonatomic,strong)SKPSMTPMessage *mail;//这里强持有一下否则会崩溃
@end
@implementation ViewController
- (void)viewDidLoad
{
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 40, 320, 50);
[button setTitle:@"Mail"forState:UIControlStateNormal];
[button addTarget:selfaction:@selector(sendEMail)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview: button];
}
//点击按钮后,触发这个方法
-(void)sendEMail {
SKPSMTPMessage *mail = [[SKPSMTPMessagealloc]init];
[mail setSubject:@"我是主题"]; // 设置邮件主题
[mail setToEmail:@"xxxx@example.com"];// 目标邮箱
[mail setFromEmail:@"1234@163.com"];// 发送者邮箱
[mailsetRelayHost:@"applesmtp.163.com"];//发送邮件代理服务器(注意applesmtp smtp 都可以)
[mail setRequiresAuth:YES];
[mail setLogin:@"1234@163.com"];// 发送者邮箱账号
// [mail setPass:@"qwer43"]; // 发送者邮箱密码
[mailsetPass:@"xyxyxyxy"];//发送者邮箱密码(注意这里 不是邮箱密码 是邮箱->设置->客户端授权密码)
[mail setWantsSecure:YES]; // 需要加密
[mail setDelegate:self];
// 设置邮件正文内容:
NSString *content = [NSStringstringWithCString:"测试内容" encoding:NSUTF8StringEncoding];
NSDictionary *plainPart =@{kSKPSMTPPartContentTypeKey :@"text/plain",kSKPSMTPPartMessageKey : content, kSKPSMTPPartContentTransferEncodingKey :@"8bit"};
注意:要发附件的话这个附件必须有 ,如果vcfData为空的话整个工程会崩溃
// 添加附件(以下代码可在SKPSMTPMessage库的DMEO里找到):
NSString *vcfPath = [[NSBundlemainBundle]pathForResource:@"test"ofType:@"vcf"];
NSData *vcfData = [NSDatadataWithContentsOfFile:vcfPath];
NSDictionary *vcfPart = [NSDictionarydictionaryWithObjectsAndKeys:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"test.vcf\"",kSKPSMTPPartContentTypeKey,
@"attachment;\r\n\tfilename=\"test.vcf\"",kSKPSMTPPartContentDispositionKey,[vcfDataencodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
// 执行发送邮件代码:
[mail setParts:@[plainPart, vcfPart]];// 邮件首部字段、邮件内容格式和传输编码
//用GCD防止卡主线程UI
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
[mail send];
[[NSRunLoop currentRunLoop] run];//这里开启一下runloop要不然重试其他端口的操作不会进行
});
}
- (void)messageSent:(SKPSMTPMessage *)message
{
NSLog(@"%@", message);
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
NSLog(@"message - %@\nerror - %@", message, error);
//因为存在发送失败的情况,所以这里可用再次调用 sendEMail方法 我的测试情况是 一般3次就可以成功了
}
还有一个库:http://libmailcore.com