Email is used in our working frequently, we have to send emails to different people, it is too boring to send similar content to different friends manually. Python can help us to handle the task successfully, we need to use the library smtplib and email.mime.text.
I use my sina account to send message to two men, there is *
to protect my private information, you can write your own email address to replace it. We don’t write password in python code for data security, the password is delivered by command line parameters.
Please remember that we have to transfer client authorization code rather than email account password to log in with SMTP object.
#! /usr/local/bin/python3
import smtplib, sys
from email.mime.text import MIMEText
sender = 'ste*******@sina.com'
receivers = {}
receivers[ 'Demon' ] = '27*****[email protected]'
receivers[ 'StephenHot' ] = 'wei_******@hotmail.com'
subject = 'Python SMTP Test'
smtpObj = smtplib.SMTP('smtp.sina.com', 25)
smtpObj.ehlo() # http SYN, ACK
smtpObj.starttls() #encrty
smtpObj.login( sender, sys.argv[1] )
for name, email in receivers.items():
msg = MIMEText( "Dear %s, this is a message from Spheten Wei. \n"
"He was testing Python-STMP.\n"
"Please ignore it.\n\n\n"
"from:%s\n" %
( name, sender ), 'plain', 'utf-8' )
msg['From'] = sender
msg['Subject'] = 'SMTP Test'
msg['To'] = email
print( "Sending to %s..." % email )
status = smtpObj.sendmail( sender, email, msg.as_string() )
if status != {}:
print( 'there was a problem, receiver is %s, status is %s' % ( email, status ) )
smtpObj.quit()
We have to write from: ${sender}
in our content because sina server checks it and determine whether to respond to the sending request.