iOS下發郵件目前有兩種方式,利用openURL打開iOS email app和利用MFMailComposeViewController在app內彈出email界面實現郵件發送。這兩種方式搜索一下都有很多介紹,具體就不細說瞭。下面介紹第三種方式,利用開源庫SKPSMTPMessage實現郵件發送。其實這種方式也有不少文章介紹瞭,隻是看瞭一些文章,寫得都差不多,都是貼demo裡面的代碼,沒有我需要的發送圖片和視頻附件的功能。研究和查閱瞭一些資料,將代碼綜合一下,粘貼出來方便自己和有需要的人查閱。
[cpp]
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = [defaults objectForKey:@"fromEmail"];
testMsg.toEmail = [defaults objectForKey:@"toEmail"];
testMsg.bccEmail = [defaults objectForKey:@"bccEmal"];
testMsg.relayHost = [defaults objectForKey:@"relayHost"];
testMsg.requiresAuth = [[defaults objectForKey:@"requiresAuth"] boolValue];
if (testMsg.requiresAuth) {
testMsg.login = [defaults objectForKey:@"login"];
testMsg.pass = [defaults objectForKey:@"pass"];
}
testMsg.wantsSecure = [[defaults objectForKey:@"wantsSecure"] boolValue]; // smtp.gmail.com doesn't work without TLS!
testMsg.subject = @"SMTPMessage Test Message";
//testMsg.bccEmail = @"testbcc@test.com";
// Only do this for self-signed certs!
// testMsg.validateSSLChain = NO;
testMsg.delegate = self;
//文字信息
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
@"This is a tést messåge.",kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
//聯系人信息
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];
//圖片和視頻附件
//attach image
NSString *imgPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
NSData *imgData = [NSData dataWithContentsOfFile:imgPath];
NSDictionary *imagePart = [NSDictionary dictionaryWithObjectsAndKeys:@"image/jpg;\r\n\tx-unix-mode=0644;\r\n\tname=\"test.jpg\"",kSKPSMTPPartContentTypeKey,
@"attachment;\r\n\tfilename=\"test.jpg\"",kSKPSMTPPartContentDispositionKey,[imgData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
//attach video
NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"video" ofType:@"mov"];
NSData *videoData = [NSData dataWithContentsOfFile: videoPath];
NSDictionary *videoPart = [NSDictionary dictionaryWithObjectsAndKeys:@"video/quicktime;\r\n\tx-unix-mode=0644;\r\n\tname=\"video.mov\"",kSKPSMTPPartContentTypeKey,
@"attachment;\r\n\tfilename=\"video.mov\"",kSKPSMTPPartContentDispositionKey,[videoData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,vcfPart, imagePart, videoPart, nil];
[testMsg send];
代碼是在Demo基礎上修改,經過測試,可以正常發送帶附件的email。