为什么我的MFMailComposeViewController发送邮件不起作用?

7
我从这里找到了这份源代码,并尝试使用它发送邮件。虽然成功得到了“MFMailComposeResultSent”消息,但实际上并没有发送邮件。我不明白为什么会出现这种情况。此外,虽然我已经将图像转换成NSData并附加到了邮件中,但在邮件撰写视图中却没有显示出来。这段代码存在什么问题呢?实际上,我只需要调用本地的邮件应用程序并在其中附加一张图片,但我听说没有办法在调用本地应用程序时附加文件。请告诉我我的代码有什么问题。问题1:无法从邮件撰写视图中发送邮件,问题2:无法显示附加的图片。最好的解决方法是,在本地邮件应用程序中运行附带图片的操作。期待您的回答,谢谢。
-(void) sendMail
{
NSLog(@"Mail");
MFMailComposeViewController *mfMailView = [[MFMailComposeViewController alloc]init];
NSData *imgData = UIImagePNGRepresentation(imgPreview.image);
mfMailView.mailComposeDelegate = self;

[mfMailView addAttachmentData:imgData mimeType:@"image/png" fileName:@"Me.png"];

//also tried this
//[mfMailView addAttachmentData:imgData mimeType:@"image/png" fileName:@"Me"];

[mfMailView setSubject:@"TE~st"];

[mfMailView setMessageBody:@"Download Me~!" isHTML:YES];
[self presentModalViewController:mfMailView animated:YES];
}

-(void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result) {
    case MFMailComposeResultCancelled:
        NSLog(@"cancel?");
        break;
    case MFMailComposeResultSaved:
        NSLog(@"saved?");
        break;
    case MFMailComposeResultSent:
        NSLog(@"Sent succed");
        [controller dismissModalViewControllerAnimated:YES];
        break;
    case MFMailComposeResultFailed:
        NSLog(@"sent failue");
        NSLog(@"%@",error);
        break;
    default:
        break;
}
}

你是通过模拟器还是你的设备发送的? - shabbirv
你的设备是否连接到网络?我认为,当你获得MFMailComposeResultSent时,它实际上意味着已成功告诉邮件应用程序发送电子邮件,但如果你没有网络,它可能会被排队等待发送。 - Stew
@shabzco。在模拟器上发送是否可行? - Gajendra K Chauhan
3个回答

4
  1. 确保您在设置中配置了帐户。
  2. 我找不到任何收件人?

您可以参考此链接:链接


当然,我有网络连接。我在邮件视图中手动输入了收件人,而不是在代码中。 - user1471568
1
哦糟糕,我发现我的手机上邮件账户没有配置。(实际上已经配置了,但iCloud账户出了问题。)非常感谢。有没有办法检查用户配置的邮件账户? - user1471568
MFMailComposeViewController上有一个+ (BOOL)canSendMail;方法,它肯定会检查是否配置了任何邮件帐户。如果您配置不正确的帐户,则认为这是用户问题,而不是您可以在代码中检测到的问题。 - Stew
只需打开iPhone邮件应用程序,它将从MFMailComposeViewController发送发件箱中的待处理邮件。 - M.Yessir

0

Swift 5和Xcode 12.5.1...

如果存在,请打开配置邮件或转到其他选项...

声明反馈邮件

let recipientEmail = "feedback@gmail.com"

点击事件

      @IBAction func openEmail(_ sender: Any) {
        
        if MFMailComposeViewController.canSendMail() {
            self.sendEmail(title: "Subject")
        } else {
            if let emailUrl = createEmailUrl(to: recipientEmail,
                                             subject: "Subject", body: "Send from my iPhone") {
                UIApplication.shared.open(emailUrl)
            }
        }
    }


func sendEmail(title : String){
    let EmialVC = configuredMailForWriteWithUs(title: title)
    self.present(EmialVC, animated: true, completion: nil)
}

       private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
           let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
           let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

           let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
           let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
           let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
           let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
           let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")

           if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
               return gmailUrl
           } else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
               return outlookUrl
           } else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
               return yahooMail
           } else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
               return sparkUrl
           }

           return defaultUrl
       }

如果用户没有任何邮件配置,它将要求提供其他邮件选项...

0
在Swift 3中,您可以使用以下清晰的代码:
 @IBAction func sendMail(_ sender: Any) {

        print(MFMailComposeViewController.canSendMail())
        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["test@test.com"])
            mail.setMessageBody("<p>This is test Mail!</p>", isHTML: true)

            present(mail, animated: true)
        } else {
             let email = "test@test.com"
             if let url = URL(string: "mailto:\(email)") {
             UIApplication.shared.open(url)
             }

        }


    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true)
        switch result {
        case .cancelled:
            print("Mail cancelled")
        case .saved:
            print("Mail saved")
        case .sent:
            self.allertInfo(_title: "Mail Info", _message: "Mail is sent successfuly", _actionTitle: "OK")
            print("Mail sent")
        case .failed:
            self.allertInfo(_title: "Mail Info", _message: "Mail isn't sent.",
_actionTitle: "OK")
            print("Mail sent failure: \(error?.localizedDescription)")
        default:
            break
        }

    }

    func allertInfo(_title:String, _message:String, _actionTitle:String) {

        let alert = UIAlertController(title: _title, message: _message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: _actionTitle, style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接