从 iOS 应用程序发送电子邮件

Send email from iOS app

我正在使用 Swift 3 构建一个非常基本的 iOS 应用程序。它包含一个包含以下字段的处方集:

我想通过电子邮件发送此数据。使用字段 Email 作为接收者,其余字段在 Body 中。

我希望发件人始终相同,我有一个 Wordpress 后端,我不知道我是否必须有端点才能执行此操作(也许使用 PHP 发送邮件,而不是直接从应用程序发送邮件) .

我尝试使用 MFMailComposeViewController,但这会打开发送电子邮件的模式,并且需要在设备上配置电子邮件帐户。

知道怎么做吗?

使用网络服务将您的数据发送到您的网络服务器,然后从那里向 Receiver/Recipients 发送电子邮件。 Web 服务器可以在不通知(移动应用程序)用户的情况下发送电子邮件。

您可以在 Web 服务器上设置一个帐户,该帐户可以从一个帐户发送所有电子邮件。在您的情况下,使用网络服务从网络服务器发送电子邮件是最佳选择。

iOS won't allow to send an e-mail without using MFMailComposeViewController.

您需要一种服务来发送您的电子邮件,这可以是您自己的 WebService,或者您可以选择许多可用服务中的一种,例如 sendgrid.com,这在您的 Swift 中很容易实现应用程序并有 40k 个免费电子邮件限制。

这是一个使用 sendgrid.com 服务的 Swift 3 示例:

注意:在使用此方法之前,请在 sendgrid.com 注册以获取 api_userapi_key 值。

func sendEmail(_ email: String, recipientName: String, subject: String, text: String) {
    let params = [
        "api_user": ENTER_YOUR_API_USER,
        "api_key": HERE_YOU_ENTER_API_KEY,
        "to": email,
        "toname": recipientName,
        "subject": subject,
        "html": text,
        "from": "noreply@example.com"
    ]
    var parts: [String] = []
    for (k, v) in params {
        let key = String(describing: k).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        let value = String(describing: v).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        parts.append(String(format: "%@=%@", key!, value!))
    }
    guard let url = URL(string: String(format: "%@?%@", "https://api.sendgrid.com/api/mail.send.json", parts.joined(separator: "&"))) else { return }

    let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)
    let task = session.dataTask(with: url, completionHandler: {
        (data, response, error) in
        if (error == nil) {
            print("Email delivered!")
        } else {
            print("Email could not be delivered!")
        }
    })
    task.resume()
    session.finishTasksAndInvalidate()
}

用法-1 (plain/text):

sendEmail("recipient@email.com", recipientName: "Recipient Name", subject: "PlainText", text: "This is a PlainText test email.")

用法-2 (html):

sendEmail("recipient@email.com", recipientName: "", subject: "HTML Test", text: "<html><div>This is a <b>HTML</b> test email.</div></html>")