Cristian F.
Cristian F.

Reputation: 480

Python - How can I send email with attachments in Python using gmail?

As you may well know, some mail addresses need to turn off security for less secure apps in gmail. Turning off options works like a charm with smtplib and attachments, but without turning off it don't works at all.

Then I discovered an API way using Auth 2.0 in ezgmail module, and it can send emails very easy, but however the attachments are not attached well. they have some problem at encoded, because they don't display well the documents.

The code I ended up with is:

import ezgmail
import os, sys, glob
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

pathFile = '<path>'
folder = os.getcwd()

def compose():
    # email_from = '<my email>'

    subject = 'Hello,'
    body = '''Here I put the text I want.'''

    return [subject, body]

def send_email(email_to):

    subject, body = compose()
    ezgmail.EMAIL_ADDRESS = '<my email>' # email_from

    os.chdir(pathFile)
    list_pdfs = glob.glob('*.pdf')
    file1 = max(list_pdfs, key=os.path.getctime) # select latest file

    # this should do the *encode part*
    attachment = open(file1, 'rb')
    file = MIMEBase('application','octet-stream')
    file.set_payload((attachment).read())
    encoders.encode_base64(file)

    os.chdir(folder)

    ezgmail.send(email_to, subject, body, file.as_string())
    print("Mail sent")

send_email([email protected])

And the question it's : how to attach properly documents (pdf, word, excel) to ezgmail ?

Upvotes: 1

Views: 1029

Answers (1)

Psionman
Psionman

Reputation: 3699

The attachment(s) need to be a string (or list of strings) representing the path(s) to the document(s):

def send_email(email_to):

    subject, body = compose()
    ezgmail.EMAIL_ADDRESS = '<my email>' # email_from

    os.chdir(pathFile)
    list_pdfs = glob.glob('*.pdf')
    file1 = max(list_pdfs, key=os.path.getctime) # select latest file

    os.chdir(folder)

    ezgmail.send(email_to, subject, body, os.sep.join([pathFile, file1]))
    print("Mail sent")

The encoding is a separate issue.

The author says:

EZGmail isn't meant to be comprehensive and do everything the Gmail API lets you do, it's meant to make the simple things simple

It does attempt to do the MIME conversion, but there is nothing specific for pdf files

the following code needs to be inserted into the EZgmail module in the _createMessageWithAttachments method:

elif sub_type == 'pdf':
    mimePart = MIMEBase('application','octet-stream')
    mimePart.set_payload((fp).read())
    encoders.encode_base64(mimePart)

and you need to import encoders from email

Upvotes: 1

Related Questions