2017-02-17 178 views
0

我正在使用httplib2和Mailgun API來發送電子郵件附件,這是我使用Google Drive下載的,電子郵件正在發送但沒有附件..以下是我的代碼..如何用Mailgun使用python httplib2發送電子郵件附件

DRIVE = discovery.build('drive', 'v3', http=http_auth) 

     request = DRIVE.files().export_media(fileId=file_id, mimeType='application/pdf') 

     fh = io.BytesIO() 
     downloader = MediaIoBaseDownload(fh, request) 

     done = False 
     while done is False: 
      status, done = downloader.next_chunk() 
      logging.info("Download %d%%." % int(status.progress() * 100)) 

     messages = { 
      "from": sender, 
      "to": recipient, 
      "subject": 'Attachment Mail from Mailgun', 
      "text": 'Testing', 
      "attachment": fh.getvalue() 
     } 

     url = URL 

     data = { 
      "from": messages['from'], 
      "to": messages['to'], 
      "subject": messages['subject'], 
      "text": messages['text'], 
      "attachment": messages['attachment'] 
     } 

     pl = urllib.urlencode(data) 

     http = httplib2.Http() 
     http.add_credentials('api', API) 

     resp, content = http.request(
      url, 'POST', pl, 
      headers={"Content-Type": "application/x-www-form-urlencoded"}) 

回答

0

我們使用mailgun API發送使用Appenginecloud storage閱讀電子郵件,同樣的原則將適用於google drive

我會建議的第一件事就是尋找到StringIO。它允許您以比BytesIO更簡單的方式模擬appengine沙箱內的文件,但都產生python稱爲支持.read()file objects,所以這應該適用於兩者。

將文件作爲file like object後,您只需將其正確傳遞給API即可。以下示例使用requests庫,因爲它使用文件進行POST很容易,並且與appengine兼容。

請注意,在這種情況下open(FILE_PATH_1, 'rb')file like object,您只需要更換,以你的文件對象:

def send_complex_message(): 
    return requests.post("https://api.mailgun.net/v2/DOMAIN/messages", 
      auth=("api", "key-SECRET"), 
      files={ 
       "attachment[0]": ("FileName1.ext", open(FILE_PATH_1, 'rb')), 
       "attachment[1]": ("FileName2.ext", open(FILE_PATH_2, 'rb')) 
      }, 
      data={"from": "FROM_EMAIL", 
       "to": [TO_EMAIL], 
       "subject": SUBJECT, 
       "html": HTML_CONTENT 
      }) 
相關問題