Send e-mail using Python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.