Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How send Email using Gmail api in swift

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

like image 677
jose920405 Avatar asked Dec 14 '22 11:12

jose920405


2 Answers

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))
    }
like image 199
jose920405 Avatar answered Dec 23 '22 09:12

jose920405


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!")
    }
} 
like image 42
Manuel Escrig Avatar answered Dec 23 '22 10:12

Manuel Escrig