Excerpt from: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001432005226355aadb8d4b2f3f42f6b1d6f2c5bd8d5263000
SMTP is the protocol that sends messages, and Python's built-in support for SMTP can send plain text messages, HTML messages, and messages with attachments.
smtplib
python supports SMTP with email
two modules email
, which are responsible for structuring the message and sending the message. smtplib
First, let's construct one of the simplest plain text messages:
from email.mime.text import mimetextmsg = Mimetext (" hello, send by Python ... ", " plain , " Utf-8 )
Notice that when MIMEText
the object is constructed, the first parameter is the message body, the second parameter is the MIME subtype, the incoming ‘plain‘
expression is plain text, the final MIME is ‘text/plain‘
, and finally it must be used utf-8
Encoding guarantees multiple language compatibility.
Then, send it out via SMTP:
fromEmail.mime.textImportmimetextmsg= Mimetext ('Hello, send by Python ...','Plain','Utf-8')#Enter your email address and password:FROM_ADDR = input ('From :') Password= Input ('Password:')#Enter recipient address:TO_ADDR = input ('To :')#Enter the SMTP server address:Smtp_server = input ('SMTP Server:')ImportSmtplib#the SMTP protocol default port isServer = Smtplib. SMTP (Smtp_server, 25) Server.set_debuglevel (1) server.login (from_addr, password) server.sendmail (from_addr, [to_addr], msg.as_string ()) Server.quit ()
set_debuglevel(1)
We can print out all the information that interacts with the SMTP server. The SMTP protocol is a simple text command and response. method is used to log on sendmail()
to an SMTP server by sending an e-mail message because it can be list
sent to more than one person at a time, so the message body is a login()
str
and as_string()
turn the MIMEText
object into str
A.
If all goes well, you can receive the email we just sent in the recipient's mailbox:
Python Learning Note (47) SMTP Send mail