Attach a txt file in Python smtplib

2019-01-11 16:39发布

问题:

I am sending a plain text email as follows:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_message():
    msg = MIMEMultipart('alternative')
    s = smtplib.SMTP('smtp.sendgrid.net', 587)
    s.login(USERNAME, PASSWORD)

    toEmail, fromEmail = to@email.com, from@email.com
    msg['Subject'] = 'subject'
    msg['From'] = fromEmail
    body = 'This is the message'

    content = MIMEText(body, 'plain')
    msg.attach(content)
    s.sendmail(fromEmail, toEmail, msg.as_string())

In addition to this message, I would like to attach a txt file, 'log_file.txt'. How would I attach a txt file here?

回答1:

The same way, using msg.attach:

from email.mime.text import MIMEText

filename = "text.txt"
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)           
msg.attach(attachment)


回答2:

It works for me

sender = 'spider@fromdomain.com'
receivers = 'who'

msg = MIMEMultipart()
msg['Subject'] = 'subject'
msg['From'] = 'spider man'
msg['To'] = 'who@gmail.com'
file='myfile.xls'

msg.attach(MIMEText("Labour"))
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file, 'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attachment)

print('Send email.')
conn.sendmail(sender, receivers, msg.as_string())
conn.close()