I have been playing with Postfix for the last couple of days. I have already posted a perfect php class for sending email with attachments in a previous post. The Python example I posted earlier does the job for me but it was not perfect like the php one.
After digging a while, I found a nice way to do the same for python as well. I have just tested the codes and the result is perfectly what I desired 🙂
Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import smtplib 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 os def sendMail(to, fro, subject, text, files=[],server="localhost"): assert type(to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(file,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(fro, to, msg.as_string() ) smtp.close() # Example: sendMail(['maSnun <masnun@gmail.com>'],'phpGeek <masnun@leevio.com>','Hello Python!','Heya buddy! Say hello to Python! :)',['masnun.py','masnun.php']) |
8 replies on “Sending Mail Via Postfix: A perfect Python Example :)”
[…] more: Sending Mail Via Postfix: A perfect Python Example « maSnun.com By admin | category: python | tags: does-the-job, last-couple, perfect-php, […]
This code (or the PHP version) isn’t exactly specific to postfix. All you need is a sendmail compatible mailer daemon installed in the system. All of the popular MTAs (postfix, exim, qmail etc) support the sendmail way of sending mail.
[…] to execute the shell command and a Postfix server. However, I came across this clean approach here, which uses smtplib to send the email. I modified my controller.py to reading the CKAN config file […]
[…] 使用这里给出的完美例子 […]
[…] Define sendmail function […]
Thank you!
You solved a tricky problem, I would like to see how the other guy use sendmail with python.
Hi Masnun,
Thanks, nice code. Worked perfectly for my server running postfix.
Have a nice day
thanks that made me spot the email lib.
We can streamline things using more up-to-date code (python 3):