python comes with two modules, smtplib and email, which are used to send emails. smtplib is responsible for sending emails, and it is a simple encapsulation of the smtp protocol. email is responsible for constructing emails.
There are three modules under the email package: MIMEText, MIMEImage, and MIMEMultipart.
Send plain text qq emails
import smtplib from import Header from import MIMEText sender = '888888@' # Mailboxes used for sending receivers = ['888888@'] # Recipients, can be multiple arbitrary mailboxes message = MIMEText('Here is the main text!', 'plain', 'utf-8') message['From'] = Header("Sender.", 'utf-8') # Sender message['To'] = Header("Receiver", 'utf-8') # Recipient subject = 'Here's the theme!' message['Subject'] = Header(subject, 'utf-8') try: # qq mailbox server hosting # Common other mailboxes correspond to the server: # qq: login password: system assigned authorization code # 163:stmp. login password: personal setup authorization code # 126:smtp. login password: personal setup authorization code # gmail: login password: email login password smtp = smtplib.SMTP_SSL('') # Login to qq mailbox, the password you need to use is the authorization code (sender, 'abcdefghijklmn') (sender, receivers, message.as_string()) () print("Mail sent successfully.") except : print("Error: Unable to send mail")
Send HTML formatted emails
html = """ <html> <body> <h2> HTML </h2> <div style='font-weight:bold'> formatted mail </div> </body> </html> """ message = MIMEText(html,'html', 'utf-8')
Send HTML formatted emails with images
html = """ <html> <body> <h2> HTML </h2> <div style='font-weight:bold'> Formatted emails with pictures </div> <img src="cid:imageTest"> </body> </html> """ message = MIMEMultipart('related') messageAlter = MIMEMultipart('alternative') (messageAlter) (MIMEText(html, 'html', 'utf-8')) # Specify the image as the current directory fp = open('', 'rb') messageImage = MIMEImage(()) () # Define the image ID, corresponding to the ID in the image messageImage.add_header('Content-ID', '<imageTest>') (messageImage)
Sending emails with attachments
from import MIMEMultipart message = MIMEMultipart() (MIMEText('这里一封带附件的邮件!', 'plain', 'utf-8')) # Add attachments # Other formats such as png, rar, doc, xls, etc. Same thing. attach = MIMEText(open('', 'rb').read(), 'base64', 'utf-8') attach["Content-Type"] = 'application/octet-stream' attach["Content-Disposition"] = 'attachment; filename=""' (attach)
that's all...python dispatchqqDetails of the example mail,More aboutpython dispatchqqPlease follow my other related articles for information on email!