Sending a message using Python is not difficult, but it is using the SMTP protocol.
The Python standard library has a built-in smtplib that sends messages only by providing the message content and the sender's credentials.
The code is as follows:
#Coding:utf-8ImportSmtplib fromEmail.mime.textImportMimetextImport TimeImportOSImportSYSdefSend_mail (Subject, body, mail_to, username, password, mail_type='Plain'): assertIsinstance (mail_to, list) = =True msg= Mimetext (Body, _subtype=Mail_type)#Defining Headingsmsg['Subject'] =subject#Define Sendermsg[' from'] =username#msg[' to'] =';'. Join (mail_to)#define send time (undefined possible mail client will not display send time)msg['Date'] = Time.strftime ('%a,%d%b%Y%h:%m:%s%z') Try: SMTP=Smtplib. SMTP ()#connect to the SMTP server,Smtp.connect ('smtp.exmail.qq.com') #User name Passwordsmtp.login (username, password) smtp.sendmail (username, mail_to, msg.as_string ()) Smtp.quit () returnTrueexceptException as E:Print "Send mail error:%s"%ereturnFalseif __name__=="__main__": ifLen (SYS.ARGV) < 2: Print 'Usage:python mail.py Object_mail'sys.exit () Subject='Hello, this is a test e-mail'Body=" "This is an email sent through our Python program, please do not reply directly" "mail_to= [sys.argv[1]] Username='[email protected]'Password= Os.getenv ('PASSWORD') Send_mail (subject, body, mail_to, username, password)
Here are a few things:
1. I set the password of the mailbox in the environment variable, can use Export password= ' XXXXXXXX ' setting
2. The sender's mailbox must have the SMTP Send service open or the program will throw an exception.
3. Use Python mail.py recipient's address to send success
Send e-mail using Python