SMTP (Simple Mail Transfer Protocol) is the Simple Mail Transfer Protocol. It is a set of rules used to transfer mail from a source address to a destination address, and it controls the way in which mail is transferred.
Python's smtplib provides a very convenient way to send emails. It simply encapsulates the smtp protocol.
Use Python to send emails with attachments:
import time
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# Third-party SMTP service
mail_host = "smtp.exmail.qq.com" # Set up the server
mail_user = "test@qq.com" # username
mail_pass = "test" # Password
sender = 'test@qq.com'
# Receive mail, which can be set as your QQ mailbox or other mailbox
receivers1 = ['test@qq.com']
receivers2 = ['test2@qq.com']
# Create an instance with attachments
message = MIMEMultipart()
# Message body content
message.attach(MIMEText('test', 'plain', 'utf-8'))
# # # ********************************** The first excel in the mail ***************************************************
att1 = MIMEText(open('name.txt', 'rb').read(), 'plain', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# # # The filename here can be written arbitrarily, what name is written, and what name is displayed in the email
att1["Content-Disposition"] = 'attachment; filename="test1"'
message.attach(att1)
# # # ********************************** The second excel in the mail ***************************************************
att2 = MIMEText(open('name.txt', 'rb').read(), 'plain', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
# # # The filename here can be written arbitrarily, what name is written, and what name is displayed in the email
att2["Content-Disposition"] = 'attachment; filename="test2"'
message.attach(att2)
# # # ********************************** -- end -- ***************************************************
message['From'] = Header("test@qq.com", 'utf-8')
message['To'] = Header("", 'utf-8')
subject = 'test'
message['Subject'] = Header(subject, 'utf-8')
# """imap.exmail.qq.com(Use SSL, port number 993) smtp.exmail.qq.com(Use SSL, port number 465)"""
try:
smtpObj = smtplib.SMTP_SSL(mail_host)
smtpObj.connect(mail_host, 465) # 25 is the SMTP port number
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers1, message.as_string())
smtpObj.sendmail(sender, receivers2, message.as_string())
print("Mail sent successfully")
except smtplib.SMTPException:
print("Error: Unable to send mail")