How send Email using Gmail api in swift

10,378

Solution 1

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))
    }

Solution 2

If your goal is to send an email I suggest using the MailCore library for iOS. In the documentation there are examples just in Objective-c but it is compatible with Swift

This is an example of how to send an email with MailCore and Swift:

var smtpSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.username = "[email protected]"
smtpSession.password = "xxxxxxxxxxxxxxxx"
smtpSession.port = 465
smtpSession.authType = MCOAuthType.SASLPlain
smtpSession.connectionType = MCOConnectionType.TLS
smtpSession.connectionLogger = {(connectionID, type, data) in
    if data != nil {
        if let string = NSString(data: data, encoding: NSUTF8StringEncoding){
            NSLog("Connectionlogger: \(string)")
        }
    }
}

var builder = MCOMessageBuilder()
builder.header.to = [MCOAddress(displayName: "Rool", mailbox: "[email protected]")]
builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "[email protected]")
builder.header.subject = "My message"
builder.htmlBody = "Yo Rool, this is a test message!"

let rfc822Data = builder.data()
let sendOperation = smtpSession.sendOperationWithData(rfc822Data)
sendOperation.start { (error) -> Void in
    if (error != nil) {
        NSLog("Error sending email: \(error)")
    } else {
        NSLog("Successfully sent email!")
    }
} 

Solution 3

Here is the final solution I have finally make it work :

Podfile :

pod 'GoogleAPIClient/Gmail'

Sample Swift 5 code:

import Foundation
import GoogleAPIClient

class GMailManager {

    let service = GTLServiceGmail()

    func sendEmail() {

        guard let query = GTLQueryGmail.queryForUsersMessagesSend(with: nil) else {
            return
        }

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

        query.message = gtlMessage

        self.service.executeQuery(query, completionHandler: { (ticket, response, error) -> Void in
            print("ticket \(String(describing: ticket))")
            print("response \(String(describing: response))")
            print("error \(String(describing: error))")
        })
    }

    func generateRawString() -> String {

        let dateFormatter:DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"; //RFC2822-Format
        let todayString:String = dateFormatter.string(from: NSDate() as Date)

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

        print("message \(rawMessage)")

        return GTLEncodeWebSafeBase64(rawMessage.data(using: String.Encoding.utf8))
    }
}
Share:
10,378

Related videos on Youtube

jose920405
Author by

jose920405

Updated on October 09, 2022

Comments

  • jose920405
    jose920405 over 1 year

    The Gmail Api has no clear documentation on how to do this, I have been trying with this but there are many things that are in the air.

    I have sought external sources such. Source 1 and Source 2. The first seems to use the potential of the api, using the function queryForUsersMessagesSendWithUploadParameters.

    While the second is about a little more. Although this in Objective-C is not a problem, except for the GTMMIMEDocument object, which do not know where or if it is obtained or a library.

    My question is if someone has a somewhat cleaner and / or code easier to understand, or a better guide in which to send an email

  • jose920405
    jose920405 over 8 years
    Thank you. But I need to use gmail api for this. Since the application is fully linked with gmail. To get and send emails, and most importantly is that I need the gmail id generated for logic subsequent
  • Isuru
    Isuru over 8 years
    Quick side note if you're using MailCore, sometimes gmail may prevent logging in, then you have to go to your gmail account and enable this setting.
  • jose920405
    jose920405 over 8 years
    Any example for add attachment to mail?
  • pondermatic
    pondermatic about 8 years
    Keep in mind you have to "#import "GTLBase64.h" in your bridging header file.
  • footyapps27
    footyapps27 about 8 years
    Thanks for the post!
  • gbotha
    gbotha almost 8 years
    I'll looking to add an attachment as well. Did anyone ever figure this out for Gmail API and SWIFT?
  • gbotha
    gbotha almost 8 years
    I get an error for MEMailMessageModel "Use of undeclared type MEMailMessageModel. What do I need to add to support i?
  • ySeN
    ySeN almost 8 years
    as you see, 'MEMailMessageModel' is self custom model. just say you should create you model and base contains (threadID, messageID, references, subject, fromUserInformation, toUserInformation)
  • Niraj
    Niraj about 6 years
    What if Email Message Body has HTML content? Above answer is working fine for Plain Text messages only. For messages with HTML Tags the mail is being sent but when received it shows raw HTML tags as it is, instead of proper HTML output.
  • user3310076
    user3310076 about 5 years
    Gmail API for iOS is clumsy. I added pod 'GoogleAPIClientForREST' and added few generated gmail files. I'm not even able to declare var gtlMessage = GTLGmailMessage(). Any help?
  • vofili
    vofili over 4 years
    GMail API for iOS is a complete mess. I'm stuck here trying to get authorization for API calls after importing the GoogleAPIClientForREST / Gmail. Its documentation is essentially non existent
  • vofili
    vofili over 4 years
    please can you show how you Authorized the GTLRGmailService service
  • vofili
    vofili over 4 years
    I eventually found a super cool and super simple library that wraps all the Obj C inconsistency and exposes a simple interface. Thank and Bless the Author: Jonas-Taha El Sesiy . GitHub: github.com/elsesiy/GAppAuth
  • Abdul Nasir B A
    Abdul Nasir B A almost 4 years
    @Cockurt, I try to use your code and I am getting following error, can you please describe briefly. Error Domain=com.google.GTLJSONRPCErrorDomain Code=401 "(Login Required)"