1. 程式人生 > >iOS 呼叫系統傳送郵件

iOS 呼叫系統傳送郵件

第一步

匯入messageUI.framework框架

第二步

匯入標頭檔案

#import <MessageUI/MessageUI.h>

第三步

@property (nonatomic,strong)  MFMailComposeViewController *mailComposer;

準守協議<MFMailComposeViewControllerDelegate>

第四步

在點選事件裡

-(void)gotoEmail:(UITapGestureRecognizer *)tap{
    NSString *email = objc_getAssociatedObject(tap, "firstObject");
    if ([MFMailComposeViewController canSendMail]) { // 使用者已設定郵件賬戶
    
    }else{
        [SVProgressHUD showInfoWithStatus:@"無郵件帳戶,請設定郵件帳戶來發送電子郵件"];
        return;
    }
     if ([MFMessageComposeViewController canSendText] == YES) {
         _mailComposer = [[MFMailComposeViewController alloc]init];
         _mailComposer.mailComposeDelegate = self;
         [_mailComposer setSubject:@""];
         NSArray *arr = @[email];
         //收件人
         [_mailComposer setToRecipients:arr];
         // 設定郵件主題
         //[_mailComposer setSubject:@"我是郵件主題"];
         // 設定密抄送
         //[_mailComposer setBccRecipients:@[@"

[email protected]"]];
         // 設定抄送人
         //[_mailComposer setCcRecipients:@[@"[email protected]"]];
         // 如使用HTML格式,則為以下程式碼
         //    [_mailComposer setMessageBody:@"<html><body><p>Hello</p><p>World!</p></body></html>" isHTML:YES];
         /*
          //新增附件
         UIImage *image = [UIImage imageNamed:@"image"];
         NSData *imageData = UIImagePNGRepresentation(image);
         [_mailComposer addAttachmentData:imageData mimeType:@"" fileName:@"custom.png"];
         NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"];
         NSData *pdf = [NSData dataWithContentsOfFile:file];
         [_mailComposer addAttachmentData:pdf mimeType:@"" fileName:@"7天精通IOS"];
         */
         
         [_mailComposer setMessageBody:@"你好,很高興認識你" isHTML:NO];
         [self presentViewController:_mailComposer animated:YES completion:nil];
     }else{
         [SVProgressHUD showInfoWithStatus:@"裝置不支援"];
     }
}

第五步

代理方法

-(void)mailComposeController:(MFMailComposeViewController *)controller
         didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    if (result) {
        YYLog(@"Result : %ld",(long)result);
    }
    if (error) {
        YYLog(@"Error : %@",error);
    }
    switch (result)
    {
        case MFMailComposeResultCancelled: // 使用者取消編輯
            YYLog(@"Mail send canceled...");
            break;
        case MFMailComposeResultSaved: // 使用者儲存郵件
            YYLog(@"Mail saved...");
            break;
        case MFMailComposeResultSent: // 使用者點擊發送
            YYLog(@"Mail sent...");
            break;
        case MFMailComposeResultFailed: // 使用者嘗試儲存或傳送郵件失敗
            YYLog(@"Mail send errored: %@...", [error localizedDescription]);
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}