Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching a single file to an e-mail

Please forgive me up front. When I've tried to research this question I end up looking at code that I simply can't comprehend. I have about 3 hours of experience with Python and am probably attempting more than I can handle.

The problem is simple. I can successfully call Python from R (my analysis software) to send an e-mail. Adding the message, subject, to, and from fields I can do. I'd like to be able to send an attachment. Life would be great if I could send just one attachment.

The code I have thus far is

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import email.utils

fromaddr = '[email protected]'
toaddrs  = '[email protected]'
msg = MIMEMultipart(MIMEText('This is the body of the e-mail'))
msg['From'] = email.utils.formataddr(('Benjamin Nutter', fromaddr))
msg['To'] = email.utils.formataddr(('Benjamin Nutter', toaddrs))
msg['Subject'] = 'Simple test message'
f = 'filename.pdf'
part=MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' %    os.path.basename(f))
msg.attach(part)

"username = 'user'
"password = 'pw'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()

When I run this code, I get the message string payload expected: [type 'list'] (but with < not [)

I'm at my limit for self-learning today. I'm hoping this is an obvious fix to someone more experienced than myself.

I hope you're all having a great day.

like image 990
Benjamin Avatar asked Nov 14 '22 15:11

Benjamin


1 Answers

You might try using 'mailer' instead of trying to use SMTP directly. Mailer can be found here.

Here is some simple code that shows how it works.

messages=[]
message = mailer.Message()
message.attach('filename.txt')
message.From = 'Cool guy <[email protected]>'
message.To = 'Random Dude <[email protected]>'
message.Cc = 'Cards Fan <[email protected]>'
message.Subject = 'Test Email'
message.body = 'Here is the body of the email.'
messages.append(message)

emailer = mailer.Mailer(smtphost.example.com)
emailer.send(messages)

I cobbled this together from some examples I had locally. The mailer page linked above also shows other examples. Once I found this code, I converted all my other python email code to use this package.

like image 55
Mark Avatar answered Jan 06 '23 22:01

Mark