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.
Gmail Api没有关于如何执行此操作的明确文档,我一直在尝试这一点,但有许多事情在空中。
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
.
我曾寻求过这样的外部资源。源1和源2.第一个似乎使用api的潜力,使用函数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.
而第二个是多一点。虽然这在Objective-C中不是问题,但GTMMIMEDocument对象除外,它不知道在何处或是否获得它或库。
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
我的问题是,是否有人更容易理解更清洁和/或代码,或者更好地发送电子邮件的指南
3 个解决方案
#1
8
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))
}
#2
1
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
如果您的目标是发送电子邮件,我建议使用适用于iOS的MailCore库。在文档中,Objective-c中有一些示例,但它与Swift兼容
This is an example of how to send an email with MailCore and 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
According to Google API documentation(https://developers.google.com/gmail/api/guides/sending), we can know there are have two ways can help you send message success(draft.send, message.send). without a doubt, both of them use api are different, but the result is the same. As you give one of the above way can got that, we just call it message.send. With another way is draft.send, so we should upload "UploadParameters" to Gmail draft, after we upload success, we can get some message about gmail draft. At last, we should send mail content, when we send success, the draft message will automatic delete. Code goes be as follows:
根据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))
}
#1
8
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))
}
#2
1
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
如果您的目标是发送电子邮件,我建议使用适用于iOS的MailCore库。在文档中,Objective-c中有一些示例,但它与Swift兼容
This is an example of how to send an email with MailCore and 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
According to Google API documentation(https://developers.google.com/gmail/api/guides/sending), we can know there are have two ways can help you send message success(draft.send, message.send). without a doubt, both of them use api are different, but the result is the same. As you give one of the above way can got that, we just call it message.send. With another way is draft.send, so we should upload "UploadParameters" to Gmail draft, after we upload success, we can get some message about gmail draft. At last, we should send mail content, when we send success, the draft message will automatic delete. Code goes be as follows:
根据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))
}