ios发送邮件
ios 发送邮件的一种方法(系统自带)
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
@interface ViewController ()<MFMailComposeViewControllerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if ([MFMailComposeViewController canSendMail]) { // 用户已设置邮件账户
[self sendEmailAction]; // 调用发送邮件的代码
}
}
- (void)sendEmailAction
{
// 邮件服务器
MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
// 设置邮件代理
[mailCompose setMailComposeDelegate:self];
// 设置邮件主题
[mailCompose setSubject:@"我是邮件主题"];
// 设置收件人
[mailCompose setToRecipients:@[@"1271010099@qq.com"]];
// 设置抄送人
[mailCompose setCcRecipients:@[@"1271010099@qq.com"]];
// 设置密抄送
[mailCompose setBccRecipients:@[@"1271010099@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:@"001"];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[mailCompose addAttachmentData:imageData mimeType:@"" fileName:@"custom.png"];
NSString *file = [[NSBundle mainBundle] pathForResource:@"001" ofType:@"jpg"];
NSData *jpg = [NSData dataWithContentsOfFile:file];
[mailCompose addAttachmentData:jpg mimeType:@"" fileName:@"哈哈哈哈哈"];
// 弹出邮件发送视图
[self presentViewController:mailCompose animated:YES completion:nil];
}
- (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];
}
@end