Python3 smtp Send mail
The SMTP (Simple Mail Transfer Protocol) is simply the message Transfer Protocol, which is a set of rules for sending mail from the source address to the destination, and it controls the way the letters are relayed.
Python's Smtplib provides a convenient way to send e-mails. It provides a simple encapsulation of the SMTP protocol.
Python creates SMTP object syntax as follows:
Import= smtplib. SMTP([[,[, local_hostname]])
Parameter description:
- HOST:SMTP Server host. You can specify the IP address of the host or the domain name such as: Runoob.com, which is an optional parameter.
- PORT: If you provide the host parameter, you need to specify the port number that the SMTP service uses, and the SMTP port number is typically 25.
- Local_hostname: If SMTP is on your local computer, you only need to specify the server address as localhost.
The Python SMTP object uses the SendMail method to send the message with the following syntax:
SMTP. SendMail(from_addr, To_addrs, msg[, mail_options, rcpt_options]
Parameter description:
- From_addr: Mail Sender address.
- To_addrs: String list, mailing address.
- Msg: Send Message
Notice here that the third parameter, MSG, is a string that represents the message. We know that the mail is generally composed of the title, sender, recipient, mail content, attachments, etc., when sending mail, pay attention to the format of MSG. This format is the format defined in the SMTP protocol.
Instance
Import smtplibfrom email.header Import header # used to set headers and message subject from Email.mime.text import Mimetext # Send text messages containing only simple text, introducing MIME Text can import time# used by the SMTP server used to send mail smtpserver = ' smtp.qq.com ' # send the mailbox user name and authorization code (not the password of the login mailbox) Username = ' [email protected] ' Password = ' xxxxxxxxx ' # sender and recipient sender = ' [email protected] ' receiver = ' [email protected] ' #发送的题目和内容mail_title = ' Ystraw ' ma Il_body = ' Happy to you ' # Create an instance of message = Mimetext (mail_body, ' plain ', ' utf-8 ') # message body message[' from ' = sender # sender on message messag e[' to ' = receiver # message shows the recipient message[' Subject ' = Header (mail_title, ' utf-8 ') # message subject TRY:SMTP = Smtplib. SMTP () # Create a connection Smtp.connect (smtpserver) # connection to send mail server smtp.login (username, password) # logon Server ct = ten #发送次数 For I in range (CT): smtp.sendmail (sender, receiver, message.as_string ()) # Fill in the message and send Time.sleep (5) # stay 5 sec Print (i) print ("Mail sent successfully!!!" ") Smtp.quit () #关闭连接except smtplib. Smtpexception:print ("Mail failed to send!!! ")
21-py3 e-mail