Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How insert image in HTML Body Email Swift 3?

Tags:

ios

swift3

I'm working hard in my app, but I got a problem. Need insert a image in my HTML code from Swift to send a email.

this is my code, but of course doesn't work!

var h = "<html><body leftmargin=15% topmargin=2% marginwidth=7% marginheight=7%>"
h = h + "<img width=100px src=logoICR.png>"
h = h + "</body></html>"
like image 421
Gilko Avatar asked Jun 14 '17 04:06

Gilko


1 Answers

Please try below code for insert Image inside Email HTML Body.


Code works with Swift 4.0 & 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(["[email protected]"])
        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)
    }
    
}
like image 105
Anand Nimje Avatar answered Nov 15 '22 02:11

Anand Nimje