How send Email using Gmail api in swift

前端 未结 4 1956
一个人的身影
一个人的身影 2021-01-03 08:15

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 source

4条回答
  •  粉色の甜心
    2021-01-03 08:53

    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: \r\n" +
                "To: username \r\n" +
                "Subject: Test send email\r\n\r\n" +
                "Test body"
    
            print("message \(rawMessage)")
    
            return GTLEncodeWebSafeBase64(rawMessage.data(using: String.Encoding.utf8))
        }
    }
    

提交回复
热议问题