Gmail API:如何将附件发送到swift上的草稿

时间:2015-12-14 10:24:22

标签: swift email-attachments gmail-api

最近,我的项目添加使用Gmail,所以我遇到很多关于它的问题,这让我很难过。   现在,我想知道如何将图像发送到草稿,我的代码如下:

func postEmailMessageRequest(model: MEMailMessageModel, request: CompletionRequest) {

        let uploadParameters = GTLUploadParameters()
        uploadParameters.data = "String".dataUsingEncoding(NSUTF8StringEncoding)
        uploadParameters.MIMEType = "message/rfc2822"

        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: "failure")
            }
        }
    }

    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: "success")
            } else {
                request(status: false, result: "failure")
            }
        })
    }

以上我可以发送文本成功,但我不知道如何将图像或PDF发送到草稿。

1 个答案:

答案 0 :(得分:0)

有最终代码可以发送附件电子邮件和回复电子邮件。 `

// send email
extension MENetworkUtil {

/**
 * block: typealias NetworkResponse = (status: Bool, result: AnyObject) -> Void
 *
 * model: MEMailMessageModel contains(threadID, messageID, toUsers, fromUser, ccUsers, bccUsers, subject, contentText, attachmentsModels, isReplyEmail)
 **/
func setMailReqest(model: MEMailMessageModel, responseBlock: NetworkResponse) {
    let query = GTLQueryGmail.queryForUsersMessagesSendWithUploadParameters(nil) as! GTLQueryGmail
    let message = GTLGmailMessage()

    message.threadId = model.threadID
    message.raw = getEmailRawString(model)
    query.message = message

    service.executeQuery(query) { (ticket, response, error) in
        if error == nil {
            let result = response as! GTLGmailMessage

            if model.isReply { // send reply email success
                responseBlock(status: ture, result: result)
            } else {
                responseBlock(status: ture, result: result)
            }

        } else {
            request(status: false, result: "send email failure")
            printLog(error.debugDescription)
        }
    }
}

func getEmailRawString(model: MEMailMessageModel) -> String {
    var headerMessage = ""
    headerMessage += setSimpleEmailHeader(model) // send email

    if model.isReply { // send reply email
        headerMessage += setReplyEmail(model)
    }

    if model.attachments.count > 0 { // send attachments
        headerMessage += setAttachmentsEmail(model)
    } else {
        headerMessage += "\r\n\(model.contentText)\r\n\r\n"
    }

    // it should be convert to base64 string
    return GTLEncodeWebSafeBase64(headerMessage.dataUsingEncoding(NSUTF8StringEncoding))
}

func setSimpleEmailHeader(model: MEMailMessageModel) -> String {
    var rawMessage = ""
    let fromEmail = MEGlobal.loginEmail // login google email

    // send email date
    let date = MEMailMessagelFormatUtil.coverDateFromDate(NSDate(), dateFormat: "EEE, dd MMM yyyy HH:mm:ss Z")!

    // send email subject
    let subject = "=?UTF-8?B?" + "\(GTLEncodeBase64(model.subject.dataUsingEncoding(NSUTF8StringEncoding)))" + "?="

    let toInfoStr = model.toUsersString
    let ccInfoStr = model.ccUsersString
    let fromInfoStr = model.fromUserString

    if !ccInfoStr.isEmpty {
        rawMessage += "Cc: \(ccInfoStr)\r\n"
    }

    rawMessage += "MIME-Version: 1.0\r\n"
    rawMessage += "Date: \(date)\r\n"
    rawMessage += "From: \(fromInfoStr)\r\n"
    rawMessage += "To: \(toInfoStr)\r\n"
    rawMessage += "Subject: \(subject) \r\n"

    return rawMessage
}

// send reply email you should add two properties: References/In-Reply-To
// references means the same thread messageIDs()
// In-Reply-To means you reply thread the last email messageID
func setReplyEmail(model: MEMailMessageModel) -> String { // 回复邮件样式
    var rawMessage = ""
    rawMessage = "" + "In-Reply-To: \(model.messageID)\r\n"

    if let references = model.references { // check thread has more than 1 message.
        rawMessage += "References: \(references) \(model.messageID)\r\n"
    } else {
        rawMessage += "References: \(model.messageID)\r\n"
    }

    return rawMessage
}

// the attachments email
// first of all, you should figure out 'Content-Type'
// MEMailAttachmentsModel: is constom attachment model, contains(attachment type, attachment name, data), and data should be convert NSData to Base64 String.
func setAttachmentsEmail(model: MEMailMessageModel) -> String {

    var rawMessage = ""
    rawMessage += "Content-Type: multipart/mixed; boundary=\"foo_bar_baz\"\r\n"
    rawMessage += "Content-Length: 99999999999999999999999999\r\n\r\n"
    rawMessage += "--foo_bar_baz\r\n"
    rawMessage += "Content-Type: text/plain; charset=\"UTF-8\"\r\n"
    rawMessage += "MIME-Version: 1.0\r\n\r\n"
    rawMessage += "\(model.contentText)\r\n\r\n"

    var attachments: [MEMailAttachmentsModel] = model.attachments

    for i in 0..<attachments.count {
        let attachment  = attachments[i]
        var contentType = ""
        switch attachment.attachmentType {
        case .Text:
            contentType = "text/plain"
        case .JPEG:
            contentType = "image/jpeg"
        case .PNG:
            contentType = "image/png"
        case .HTML:
            contentType = "text/html"
        case .Multipart:
            contentType = "multipart/mixed"
        case .Video:
            contentType = "video/mpeg"
        case .Application:
            contentType = "application/octet-stream"
        case .MSWord:
            contentType = "application/msword"
        case .PDF:
            contentType = "application/pdf"
        default: break
        }

        if attachment.mimeType != "" {
            contentType = attachment.mimeType
        }

        rawMessage += "--foo_bar_baz\r\n" +
            "Content-Type: \(contentType)\r\n" +
            "MIME-Version: 1.0\r\n" +
            "Content-Transfer-Encoding: base64\r\n" +
            "Content-Disposition: attachment; filename=\"\(attachment.fileName)\"\r\n" +
        "Content-Type: message/rfc822\r\n\r\n"
        rawMessage += "\(GTLEncodeBase64(attachment.fileData!))\r\n\r\n"
    }

    rawMessage += "--foo_bar_baz--"

    return rawMessage
}
}

`