Search code examples
pythonpython-3.xbase64gmail-api

How to attach excel files to Gmail using Python 3.7?


I created a function in python 3.7 to create draft emails with attached spreadsheets for all the clients. The code creates that draft email correctly and attaches the files (.xlsx) but these files can no more be opened on gmail. Not sure if this is specific to the encoding that I am using. (The files can be opened successfully on my desktop computer)

Below is the code:

def CreateMessageWithAttachment(sender, to, cc, subject, message_text, file_dir, filename):
    """Create email messages with attachment, for sending to partners"""
    message = MIMEMultipart('alternative')
    message['to'] = to
    message['from'] = sender
    message['cc'] = cc
    message['subject'] = subject
    msg = MIMEText(message_text, 'html')
    message.attach(msg)
    path = os.path.join(file_dir, filename)
    content_type, encoding = mimetypes.guess_type(path)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'

    main_type, sub_type = content_type.split('/', 1)
    #    main_type, sub_type = 'gzip', None
    fp = open(path, 'rb')
    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    fp.close()
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    return {'raw': raw}
    #return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

I am assuming, the encoding of the files is what corrupting the spreadsheets attached. Any help would be appreciated.


Solution

  • Try changing these two lines:

    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    

    To just this:

    msg = MIMEApplication(fp.read(), sub_type)