[BangPypers] Change the "From:" address using python smtplib

Gopalakrishnan Subramani gopalakrishnan.subramani at gmail.com
Tue Oct 30 18:06:00 CET 2012


As per SPF, http://en.wikipedia.org/wiki/Sender_Policy_Framework and email
server handling, your emails will be placed in junk mails in most of the
mail server.

As per your script, you  send email from an email id which is different
than the one which is used for authentication. Most of the SMTP servers
(your outgoing servers such as smtp.gmail.com) would not care what is in
the from address of MIMEMultipart or simply SMTP's FROM header.

You could add the following to forge  (although you send using differ
account), this is called as on-behalf-of.

 msg.add_header('reply-to', send_from) # 'mahadevan.m at gmail.com' would get
reply when recipient replies
 msg['From'] = send_from + ' <' + smtp_login_mail + '>' # peacefully valid
in smtp terms. many social network sites send mail using this idea

if you use custom domain, make sure you have SPF records setup.




On Tue, Oct 30, 2012 at 6:43 PM, Baskar K <baskar.krishnan at jouve.in> wrote:

> Hi, I am new to python, and I am writing the code to send a mail. It works
> but i need to change the from address of the mail but it takes the
> authentication mail id as from address. Please help me
>
>     import smtplib, 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
>
>     def send_mail(send_from, send_to, subject, text, files=[], server="
> smtp.gmail.com:587"):
>         assert type(send_to)==list
>         assert type(files)==list
>
>         msg = MIMEMultipart()
>         msg['From'] = send_from
>         msg['To'] = COMMASPACE.join(send_to)
>         msg['Date'] = formatdate(localtime=True)
>         msg['Subject'] = subject
>
>         msg.attach( MIMEText(text) )
>
>         for f in files:
>             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)
>
>         smtp = smtplib.SMTP(server)
>         smtp.ehlo()
>         smtp.starttls()
>         smtp.ehlo
>         smtp.login('baskar.krishnan at gmail.com', 'password')
>         smtp.sendmail(send_from, send_to, msg.as_string())
>         smtp.close()
>
>     files = ['Config.ini', 'mail_ini.txt']
>     send_to = ['baskar.krishnan at gmail.com']
>     send_mail('mahadevan.m at gmail.com', send_to, 'test subject', 'body
> matter', files)
>
> Thanks in advance
> Baski
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>


More information about the BangPypers mailing list