Gmail Api没有关于如何执行此操作的明确文档,我一直在尝试使用this,但有很多内容都在播出。
我已经寻求过这样的外部资源。 Source 1和Source 2。第一个似乎是使用api的潜力,使用函数queryForUsersMessagesSendWithUploadParameters
。
虽然第二个是多一点。尽管在Objective-C中这不是问题,但GTMMIMEDocument对象除外,它不知道在何处或是否获得它或库。
我的问题是,是否有人更容易理解,或者更容易理解代码,或者是更好的发送电子邮件的指南
答案 0 :(得分:9)
我找到了解决方案
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))
}
答案 1 :(得分:2)
这是我终于可以使用的最终解决方案:
Podfile:
pod 'GoogleAPIClient/Gmail'
示例Swift 5代码:
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))
}
}
答案 2 :(得分:1)
如果您的目标是发送电子邮件,我建议使用适用于iOS的MailCore库。 在文档中有Objective-c中的示例,但它与Swift兼容
这是如何使用MailCore和Swift发送电子邮件的示例:
var smtpSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.username = "matt@gmail.com"
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: "itsrool@gmail.com")]
builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "matt@gmail.com")
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!")
}
}
答案 3 :(得分:0)
根据Google API文档(https://developers.google.com/gmail/api/guides/sending),我们可以知道有两种方法可以帮助您发送消息成功(draft.send,message.send)。毫无疑问,他们两个都使用api是不同的,但结果是一样的。 正如你给出的上述方法之一可以得到的那样,我们只需将其称为message.send。另一种方式是draft.send,所以我们应该将“UploadParameters”上传到Gmail草稿,在我们上传成功之后,我们可以得到一些关于gmail草案的消息。最后,我们应该发送邮件内容,当我们发送成功时,草稿邮件会自动删除。代码如下:
func postEmailMessageRequest(model: MEMailMessageModel, request: CompletionRequest) {
let uploadParameters = GTLUploadParameters()
uploadParameters.data = model.snippet.dataUsingEncoding(NSUTF8StringEncoding)
uploadParameters.MIMEType = model.mimeType!
let query = GTLQueryGmail.queryForUsersDraftsCreateWithUploadParameters(uploadParameters) as! GTLQueryProtocol!
service.executeQuery(query) { (ticket : GTLServiceTicket!, messages : AnyObject!, error : NSError?) -> Void in
if error == nil {
let messages = (messages as! GTLGmailDraft)
messages.message.threadId = model.threadID
self.sendMailRequest(messages, model: model, request: request)
} else {
request(status: false, result: "upload success")
}
}
}
func sendMailRequest(draft: GTLGmailDraft, model: MEMailMessageModel, request: CompletionRequest) {
let query = GTLQueryGmail.queryForUsersDraftsSendWithUploadParameters(nil) as! GTLQueryGmail
draft.message.raw = self.generateRawString(model)
query.draft = draft
self.service.executeQuery(query, completionHandler: { (ticket, response, error) -> Void in
if error == nil {
request(status: true, result: "send success") // after this, the draft will be delete
} else {
request(status: false, result: "send failure")
}
})
}
func generateRawString(model: MEMailMessageModel) -> String {
let date = MEMailMessagelFormatUtil.coverDateFromDate(NSDate(), dateFormat: "EEE, dd MMM yyyy HH:mm:ss Z")! // get current date
var fromEamil = ""
if let str = NSUserDefaults.standardUserDefaults().valueForKey("userEmail") as? String {
fromEamil = str
}
var rawMessage = ""
if model.isReply { // how to reply, but how to reply the email is another question.
rawMessage = "" + "In-Reply-To: \(model.messageID!)\r\n"
if let references = model.references {
rawMessage += "References: \(references) \(model.messageID!)\r\n"
} else {
rawMessage += "References: \(model.messageID!)\r\n"
}
}
rawMessage += "Date: \(date)\r\n" +
"From: <\(fromEamil)>\r\n" +
"To: \(model.toName!) <\(model.toMail)>\r\n" +
"Subject: \(model.subject) \r\n\r\n" + "\(model.snippet)"
return GTLEncodeWebSafeBase64(rawMessage.dataUsingEncoding(NSUTF8StringEncoding))
}