如何在HTML Body Email Swift 3中插入图像?

时间:2017-06-14 04:40:17

标签: ios swift3

我在我的应用中努力工作,但我遇到了问题。 需要在我的HTML代码中插入来自Swift的图像以发送电子邮件。

这是我的代码,但当然不起作用!

var h = "<html><body leftmargin=15% topmargin=2% marginwidth=7% marginheight=7%>"
h = h + "<img width=100px src=logoICR.png>"
h = h + "</body></html>"

2 个答案:

答案 0 :(得分:5)

请尝试使用以下代码在电子邮件 HTML正文中插入图片。

代码适用于 Swift 4.0 &amp; Swift 3.1
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate{


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //MARK: - Send Email
    @IBAction func actionSendEmail(_ sender: Any) {

        if !MFMailComposeViewController.canSendMail() {
            print("Mail services are not available")
            return
        }
        let image = UIImage(named:"testImage") // Your Image
        let imageData = UIImagePNGRepresentation(image!) ?? nil
        let base64String = imageData?.base64EncodedString() ?? "" // Your String Image
        let strHtml = "<html><body><p>Header: Hello Test Email</p><p><b><img src='data:image/png;base64,\(String(describing: base64String) )'></b></p></body></html>"
        let composeVC = MFMailComposeViewController()
        composeVC.mailComposeDelegate = self
        // Configure the fields of the interface.
        composeVC.setToRecipients(["address@example.com"])
        composeVC.setSubject("Hello!")
        composeVC.setMessageBody(strHtml, isHTML: true)

        // Present the view controller modally.
        self.present(composeVC, animated: true, completion: nil)
    }

    //MARK:- MFMailCompose Delegate Methods
    func mailComposeController(_ controller: MFMailComposeViewController,
                               didFinishWith result: MFMailComposeResult, error: Error?) {
        // Dismiss the mail compose view controller.
        controller.dismiss(animated: true, completion: nil)
    }

}

答案 1 :(得分:0)

提供完整的图片路径:例如

<img width=100px src=http://example.com/images/logoICR.png>