Sending Email with Swift

Sending an email from swift 3

It will not work with simulator. Please test it on iPhone device. You can refer Apple Developer Portal - MFMailComposeViewController

How to send an email without opening the mail composer iOS swift?

Apple will not allow you to send email from the user's account without displaying a mail composer window to the user (for security reasons.) You will have to implement your own mail sending mechanism from your server if you want this (and still won't be able to send email from the user's account.)

It's not that "Apple does not have this feature." It's that it would be a huge security hole. Apple explicitly blocks third parties from sending emails from the user's account except using a mail composer, and WILL NEVER ALLOW IT.

Think about the potential for abuse if it was allowed. A spammer could release a "trojan horse" app like "flappy bird" for free: A fun, popular game. Millions of people download it. Unbeknownst to them, it starts sending out emails from their accounts, attempting to defraud their friends, or the online community at large

Send email without user interaction in iOS App]

The simple answer is "No".

It is against Apple guidelines. You cannot send mail without user interaction (action on send button).

As an alternate option, you can use power of web server/web service. Send information/data to your web service using web service request and can send an email from you web server. (Note: Mail sender id will not be email id of application user.)

You can try this but remember, it's against Apple guidelines and Apple may reject your app.

  • https://stackoverflow.com/a/5183267/5638630
  • http://iosameer.blogspot.in/2013/01/sending-e-mail-in-background-from-ios_25.html
  • https://stackoverflow.com/a/6287412/5638630

Send email from iOS app

Send your data to your web server using web service and from there send an e-mail to Receiver/Recipients. Web server can send e-mail without notifying (mobile app) user.

You can setup an account on web server that can send all e-mails from a single account. In your case, sending emails from web server using web service would be best choice.

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

Sending an email from your app with an image attached in Swift

You need to add an attachmentData to your mail, encoding your image
in an NSData. This is an example that show you how to send an email with
your image. I'm suppose that you have a UIViewController where you can put the function sendMail.

import MessageUI
class MyViewController: UIViewController, MFMailComposeViewControllerDelegate
{
// .... your stuff

func sendMail(imageView: UIImageView) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self;
mail.setCcRecipients(["yyyy@xxx.com"])
mail.setSubject("Your messagge")
mail.setMessageBody("Message body", isHTML: false)
let imageData: NSData = UIImagePNGRepresentation(imageView.image)!
mail.addAttachmentData(imageData, mimeType: "image/png", fileName: "imageName.png")
self.presentViewController(mail, animated: true, completion: nil)
}
}

}

In order to dismiss the VC, include the following method in your ViewController:

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

The documentation for this method is reported in MFMailComposeViewControllerDelegate.

SwiftUI: Send email

As you mentioned, you need to port the component to SwiftUI via UIViewControllerRepresentable.

Here's a simple implementation:

struct MailView: UIViewControllerRepresentable {

@Binding var isShowing: Bool
@Binding var result: Result<MFMailComposeResult, Error>?

class Coordinator: NSObject, MFMailComposeViewControllerDelegate {

@Binding var isShowing: Bool
@Binding var result: Result<MFMailComposeResult, Error>?

init(isShowing: Binding<Bool>,
result: Binding<Result<MFMailComposeResult, Error>?>) {
_isShowing = isShowing
_result = result
}

func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
defer {
isShowing = false
}
guard error == nil else {
self.result = .failure(error!)
return
}
self.result = .success(result)
}
}

func makeCoordinator() -> Coordinator {
return Coordinator(isShowing: $isShowing,
result: $result)
}

func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController {
let vc = MFMailComposeViewController()
vc.mailComposeDelegate = context.coordinator
return vc
}

func updateUIViewController(_ uiViewController: MFMailComposeViewController,
context: UIViewControllerRepresentableContext<MailView>) {

}
}

Usage:

struct ContentView: View {

@State var result: Result<MFMailComposeResult, Error>? = nil
@State var isShowingMailView = false

var body: some View {

VStack {
if MFMailComposeViewController.canSendMail() {
Button("Show mail view") {
self.isShowingMailView.toggle()
}
} else {
Text("Can't send emails from this device")
}
if result != nil {
Text("Result: \(String(describing: result))")
.lineLimit(nil)
}
}
.sheet(isPresented: $isShowingMailView) {
MailView(isShowing: self.$isShowingMailView, result: self.$result)
}

}

}

(Tested on iPhone 7 Plus running iOS 13 - works like a charm)

Updated for Xcode 11.4

How send Email using Gmail api in swift

I found the solution

class func sendEmail() {

var gtlMessage = GTLGmailMessage()
gtlMessage.raw = self.generateRawString()

let appd = UIApplication.sharedApplication().delegate as! AppDelegate
let query = GTLQueryGmail.queryForUsersMessagesSendWithUploadParameters(nil)
query.message = gtlMessage

appd.service.executeQuery(query, completionHandler: { (ticket, response, error) -> Void in
println("ticket \(ticket)")
println("response \(response)")
println("error \(error)")
})
}

class func generateRawString() -> String {

var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"; //RFC2822-Format
var todayString:String = dateFormatter.stringFromDate(NSDate())

var rawMessage = "" +
"Date: \(todayString)\r\n" +
"From: <mail>\r\n" +
"To: username <mail>\r\n" +
"Subject: Test send email\r\n\r\n" +
"Test body"

println("message \(rawMessage)")

return GTLEncodeWebSafeBase64(rawMessage.dataUsingEncoding(NSUTF8StringEncoding))
}


Related Topics



Leave a reply



Submit