2015-01-10 101 views
1

我試圖使用Gmail API和以下功能發送各種尺寸的電子郵件。使用Gmail API發送大型附件時出現錯誤10053

一般來說,這可是完美的作品,周邊10MB附件過(這是罕見的,但會發生),我收到Errno 10053認爲是因爲我發送包括大附件的郵件時,超時。

有沒有解決這個問題的方法,例如指定大小或增加超時限制?在Gmail API文檔中提到了大小,但我很難理解如何在Python中使用或者甚至可以提供幫助。

def CreateMessageWithAttachment(sender, to, cc, subject, 
           message_text, file_dir, filename): 
    """Create a message for an email. 

    Args: 
    sender: Email address of the sender. 
    to: Email address of the receiver. 
    subject: The subject of the email message. 
    message_text: The text of the email message. 
    file_dir: The directory containing the file to be attached. 
    filename: The name of the file to be attached. 

    Returns: 
    An object containing a base64url encoded email object. 
    """ 
    message = MIMEMultipart() 
    message['to'] = to 
    if cc != None: 
    message['cc'] = cc 
    message['from'] = sender 
    message['subject'] = subject 

    msg = MIMEText(message_text) 
    message.attach(msg) 

    path = os.path.join(file_dir, filename) 
    content_type, encoding = mimetypes.guess_type(path) 

    QCoreApplication.processEvents() 

    if content_type is None or encoding is not None: 
    content_type = 'application/octet-stream' 
    main_type, sub_type = content_type.split('/', 1) 
    if main_type == 'text': 
    fp = open(path, 'rb') 
    msg = MIMEText(fp.read(), _subtype=sub_type) 
    fp.close() 
    elif main_type == 'image': 
    fp = open(path, 'rb') 
    msg = MIMEImage(fp.read(), _subtype=sub_type) 
    fp.close() 
    elif main_type == 'audio': 
    fp = open(path, 'rb') 
    msg = MIMEAudio(fp.read(), _subtype=sub_type) 
    fp.close() 
    else: 
    fp = open(path, 'rb') 
    msg = MIMEBase(main_type, sub_type) 
    msg.set_payload(fp.read()) 
    fp.close() 
    QCoreApplication.processEvents() 

    msg.add_header('Content-Disposition', 'attachment', filename=filename) 
    message.attach(msg) 
    return {'raw': base64.urlsafe_b64encode(message.as_string())} 



def SendMessage(service, user_id, message, size): 
    """Send an email message. 

    Args: 
    service: Authorized Gmail API service instance. 
    user_id: User's email address. The special value "me" 
    can be used to indicate the authenticated user. 
    message: Message to be sent. 

    Returns: 
    Sent Message. 
    """ 

    try: 
    message = (service.users().messages().send(userId=user_id, body=message) 
       .execute()) 
    QCoreApplication.processEvents() 
    return message 
    except errors.HttpError, error: 
    pass 
+0

檢查此鏈接http://stackoverflow.com/questions/17854713/error-errno-10053 – SGC

回答

1

'g'是我的授權API背景。調用方法將調用對象上的執行。重要的是Media調用並使用media_body和body params。這導致消息被插入標籤INBOX,並且它將允許至少一個24MB文件。

我結束了兩個拷貝,因爲讀取超時太短:

f fetch 8:9 (flags INTERNALDATE RFC822.SIZE) 
* 8 FETCH (RFC822.SIZE 24000720 INTERNALDATE "19-Jul-2007 17:12:26 +0000" FLAGS (\Seen)) 
* 9 FETCH (RFC822.SIZE 24000720 INTERNALDATE "19-Jul-2007 17:12:26 +0000" FLAGS (\Seen)) 

示例代碼:

import mailbox 
import StringIO 
import googleapiclient.http 

f = 'my-mbox-file.mbox' 
params = {} 
params[ 'internalDateSource' ] = 'dateHeader' 
for m in mailbox.mbox(f, create=False): 
    message_string = m.as_string() 
    params[ 'body' ] = { 'labelIds': [ 'INBOX' ] } 

    if len(message_string) > 6000000: 
     s = StringIO.StringIO() 
     s.write(message_string) 
     params[ 'media_body' ] = googleapiclient.http.MediaIoBaseUpload(
          s, mimetype='message/rfc822') 
    else: 
     params['body']['raw'] = (
      base64.urlsafe_b64encode(message_string)) 

    g.call(g.auth.users().messages().insert, params) 

    try: 
     del params[ 'media_body' ] 
    except KeyError: 
     pass 
0

我成功插入/發送的消息具有大文件,蟒蛇代碼。 谷歌api文檔對開發人員不友好,「/上傳」問題完全不清楚,沒有很好的文檔記錄,這讓很多開發人員感到困惑。

最後一行做魔術:)

def insert_message(service, message): 
     try: 
       if message['sizeEstimate'] > 6000000: 
         insert_large_message(service, message) 
       else: 
         insert_small_message(service, message) 
     except: 
       print ('Error: ----type: %s, ----value: %s, ----traceback: %s ************' % (sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])) 

def insert_small_message(service, message): 
     body = {'raw': message['raw'],'labelIds':message['labelIds'],'internalDateSource':'dateHeader'} 
     message = service.users().messages().insert(userId='me',body=body).execute() 

def insert_large_message(service, message): 
     b = io.BytesIO() 
     message_bytes = base64.urlsafe_b64decode(str(message['raw'])) 
     b.write(message_bytes) 
     body = {'labelIds':message['labelIds'],'internalDateSource':'dateHeader'} 
     media_body = googleapiclient.http.MediaIoBaseUpload(b, mimetype='message/rfc822') 
     print('load big data!') 
     message = service.users().messages().insert(userId='me',body=body,media_body=media_body).execute() 
相關問題