未能使用Swift实现应用内电子邮件

时间:2021-03-17 07:33:45

I want to use swift to implement in-app email. When I click the button, the email window pops up. However, I am unable to send my email. Moreover, after I click cancel-delete draft, I cannot go back to the original screen.

我想用swift实现应用内的邮件。当我点击按钮时,电子邮件窗口就会弹出。然而,我无法发送我的电子邮件。另外,当我点击cancel-delete draft时,我无法回到原来的屏幕上。

import UIkit
import MessageUI


class Information : UIViewController, MFMailComposeViewControllerDelegate{

    var myMail: MFMailComposeViewController!

    @IBAction func sendReport(sender : AnyObject) {

        if(MFMailComposeViewController.canSendMail()){
            myMail = MFMailComposeViewController()

            //myMail.mailComposeDelegate

            // set the subject
            myMail.setSubject("My report")

            //To recipients
            var toRecipients = ["lipeilin@gatech.edu"]
            myMail.setToRecipients(toRecipients)

            //CC recipients
            var ccRecipients = ["tzhang85@gatech.edu"]
            myMail.setCcRecipients(ccRecipients)

            //CC recipients
            var bccRecipients = ["tzhang85@gatech.edu"]
            myMail.setBccRecipients(ccRecipients)

            //Add some text to the message body
            var sentfrom = "Email sent from my app"
            myMail.setMessageBody(sentfrom, isHTML: true)

            //Include an attachment
            var image = UIImage(named: "Gimme.png")
            var imageData = UIImageJPEGRepresentation(image, 1.0)

            myMail.addAttachmentData(imageData, mimeType: "image/jped", fileName:     "image")

            //Display the view controller
            self.presentViewController(myMail, animated: true, completion: nil)
        }
        else{
            var alert = UIAlertController(title: "Alert", message: "Your device cannot send emails", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)


        }
    }




func mailComposeController(controller: MFMailComposeViewController!,
    didFinishWithResult result: MFMailComposeResult,
    error: NSError!){

        switch(result.value){
        case MFMailComposeResultSent.value:
            println("Email sent")

        default:
            println("Whoops")
        }

        self.dismissViewControllerAnimated(true, completion: nil)

}
}

3 个解决方案

#1


10  

Since you haven't set the current view controller as the mailComposeDelegate of myMail, the mailComposeController:didFinishWithResult method isn't being called. After you init myMail, make sure to add:

由于尚未将当前视图控制器设置为myMail的mailComposeDelegate,因此不会调用mailComposeController:didFinishWithResult方法。在您初始化myMail之后,请确保添加:

myMail.mailComposeDelegate = self

and you'll be good to go

你会很高兴的。

#2


1  

In case anyone is looking for a non MFMailCompose option, here's what I did to send using Gmail's SMTP servers.

如果有人在寻找非mfmailcomposer选项,下面是我使用Gmail的SMTP服务器发送的内容。

  1. Download a zip of this repo: https://github.com/jetseven/skpsmtpmessage
  2. 下载这个repo的zip: https://github.com/jetseven/skpsmtppmessage
  3. Drag and drop the files under SMTPLibrary into your XCode project
  4. 将SMTPLibrary下的文件拖放到XCode项目中
  5. Create a new header file - MyApp-Briding-Header.h
  6. 创建一个新的头文件- MyApp-Briding-Header.h
  7. Replace new header file with this:
  8. 用以下文件替换新的头文件:
#import "Base64Transcoder.h"
#import "HSK_CFUtilities.h"
#import "NSData+Base64Additions.h"
#import "NSStream+SKPSMTPExtensions.h"
#import "SKPSMTPMessage.h"
  1. Go to Project(Targets > MyApp on the left)/Build Settings/Swift Compiler - Code Generation
  2. 进入项目(左边目标是bbbmy0应用)/构建设置/Swift编译器-代码生成
  3. Add path to header file under Objective-C Briding Header -> Debug (i.e. MyApp/MyApp-Bridging-Header.h
  4. 在Objective-C Briding header -> Debug(即MyApp/MyApp- bridging - header .h)下向header文件添加路径
  5. Go to Project/Build Phases/Compile Sources
  6. 转到项目/构建阶段/编译源。
  7. Select all .m files and click enter. Type -fno-objc-arc and hit enter.

    选择所有.m文件并单击enter。键入-fno- object -arc并单击enter。

  8. Use this code to send email:

    使用此代码发送电子邮件:

var mail = SKPSMTPMessage()       
mail.fromEmail = "fromemail@gmail.com"
mail.toEmail = "tomail@gmail.com"
mail.requiresAuth = true
mail.login = "fromemail@gmail.com"
mail.pass = "password"
mail.subject = "test subject"
mail.wantsSecure = true
mail.relayHost = "smtp.gmail.com"

mail.relayPorts = [587]

var parts: NSDictionary = [
            "kSKPSMTPPartContentTypeKey": "text/plain; charset=UTF-8",
            "kSKPSMTPPartMessageKey": "test message",
]

mail.parts = [parts]

mail.send()

Hope it helps someone. I didn't want to use the MFMailCompose option because I didn't want to have to prompt the user.

希望它能帮助一些人。我不想使用mfmailcomposer选项,因为我不想提示用户。

#3


0  

This is how I have composed my email with attached PDF file document.

这就是我如何用附件中的PDF文件编写我的电子邮件。

Just to test this example you need to drag and drop a sample PDF named "All_about_tax.pdf"

为了测试这个示例,您需要拖放一个名为“All_about_tax.pdf”的示例PDF

@IBAction func sendEmail(sender: UIButton)
    {
        //Check to see the device can send email.
        if( MFMailComposeViewController.canSendMail() )
        {
            print("Can send email.")

            let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self

            //Set to recipients
            mailComposer.setToRecipients(["your email id here"])

            //Set the subject
            mailComposer.setSubject("Tax info document pdf")

            //set mail body
            mailComposer.setMessageBody("This is what they sound like.", isHTML: true)

            if let filePath = NSBundle.mainBundle().pathForResource("All_about_tax", ofType: "pdf")
            {
                print("File path loaded.")

                if let fileData = NSData(contentsOfFile: filePath)
                {
                    print("File data loaded.")
                    mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "All_about_tax.pdf")

                }
            }

            //this will compose and present mail to user
            self.presentViewController(mailComposer, animated: true, completion: nil)
        }
        else
        {
            print("email is not supported")
        }
    }



    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

#1


10  

Since you haven't set the current view controller as the mailComposeDelegate of myMail, the mailComposeController:didFinishWithResult method isn't being called. After you init myMail, make sure to add:

由于尚未将当前视图控制器设置为myMail的mailComposeDelegate,因此不会调用mailComposeController:didFinishWithResult方法。在您初始化myMail之后,请确保添加:

myMail.mailComposeDelegate = self

and you'll be good to go

你会很高兴的。

#2


1  

In case anyone is looking for a non MFMailCompose option, here's what I did to send using Gmail's SMTP servers.

如果有人在寻找非mfmailcomposer选项,下面是我使用Gmail的SMTP服务器发送的内容。

  1. Download a zip of this repo: https://github.com/jetseven/skpsmtpmessage
  2. 下载这个repo的zip: https://github.com/jetseven/skpsmtppmessage
  3. Drag and drop the files under SMTPLibrary into your XCode project
  4. 将SMTPLibrary下的文件拖放到XCode项目中
  5. Create a new header file - MyApp-Briding-Header.h
  6. 创建一个新的头文件- MyApp-Briding-Header.h
  7. Replace new header file with this:
  8. 用以下文件替换新的头文件:
#import "Base64Transcoder.h"
#import "HSK_CFUtilities.h"
#import "NSData+Base64Additions.h"
#import "NSStream+SKPSMTPExtensions.h"
#import "SKPSMTPMessage.h"
  1. Go to Project(Targets > MyApp on the left)/Build Settings/Swift Compiler - Code Generation
  2. 进入项目(左边目标是bbbmy0应用)/构建设置/Swift编译器-代码生成
  3. Add path to header file under Objective-C Briding Header -> Debug (i.e. MyApp/MyApp-Bridging-Header.h
  4. 在Objective-C Briding header -> Debug(即MyApp/MyApp- bridging - header .h)下向header文件添加路径
  5. Go to Project/Build Phases/Compile Sources
  6. 转到项目/构建阶段/编译源。
  7. Select all .m files and click enter. Type -fno-objc-arc and hit enter.

    选择所有.m文件并单击enter。键入-fno- object -arc并单击enter。

  8. Use this code to send email:

    使用此代码发送电子邮件:

var mail = SKPSMTPMessage()       
mail.fromEmail = "fromemail@gmail.com"
mail.toEmail = "tomail@gmail.com"
mail.requiresAuth = true
mail.login = "fromemail@gmail.com"
mail.pass = "password"
mail.subject = "test subject"
mail.wantsSecure = true
mail.relayHost = "smtp.gmail.com"

mail.relayPorts = [587]

var parts: NSDictionary = [
            "kSKPSMTPPartContentTypeKey": "text/plain; charset=UTF-8",
            "kSKPSMTPPartMessageKey": "test message",
]

mail.parts = [parts]

mail.send()

Hope it helps someone. I didn't want to use the MFMailCompose option because I didn't want to have to prompt the user.

希望它能帮助一些人。我不想使用mfmailcomposer选项,因为我不想提示用户。

#3


0  

This is how I have composed my email with attached PDF file document.

这就是我如何用附件中的PDF文件编写我的电子邮件。

Just to test this example you need to drag and drop a sample PDF named "All_about_tax.pdf"

为了测试这个示例,您需要拖放一个名为“All_about_tax.pdf”的示例PDF

@IBAction func sendEmail(sender: UIButton)
    {
        //Check to see the device can send email.
        if( MFMailComposeViewController.canSendMail() )
        {
            print("Can send email.")

            let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self

            //Set to recipients
            mailComposer.setToRecipients(["your email id here"])

            //Set the subject
            mailComposer.setSubject("Tax info document pdf")

            //set mail body
            mailComposer.setMessageBody("This is what they sound like.", isHTML: true)

            if let filePath = NSBundle.mainBundle().pathForResource("All_about_tax", ofType: "pdf")
            {
                print("File path loaded.")

                if let fileData = NSData(contentsOfFile: filePath)
                {
                    print("File data loaded.")
                    mailComposer.addAttachmentData(fileData, mimeType: "application/pdf", fileName: "All_about_tax.pdf")

                }
            }

            //this will compose and present mail to user
            self.presentViewController(mailComposer, animated: true, completion: nil)
        }
        else
        {
            print("email is not supported")
        }
    }



    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }