Article directory
- 1. SMTP protocol email preparation
- 2. smtplib module
-
- 1. Use smtplib to encapsulate a mail class
- 2.Send email
- Replenish
1. SMTP protocol email preparation
Need an smtp server
2. smtplib module
The smtplib module is a module that comes with python
1. Use smtplib to encapsulate a mail class
import smtplib import logging # Add logging to maintain this good habit. Configuration is required before use. class Smtp(object): # Class name customization def __init__(self, sender, pwd, server_url, server_port): """ sender user name to log in to the SMTP server. Note that in addition to using the user name and password, you can also use a key. pwd password to log in to the SMTP server server_url SMTP server domain name or IP server_port The port opened by the SMTP service """ self.sender = sender self.smtp = smtplib.SMTP(server_url, server_port, timeout=5) # Create smtp object self.smtp.starttls() # Start TSL encryption self.smtp.login(sender, pwd) # Use password or password to obtain login credentials def mail(self, *args): # Send mail """ The two parameters are: receiving email address and content. """ self.smtp.sendmail(self.sender, args[0], args[1]) def stop_mail(self): # After the email is sent, the connection needs to be closed and resources released. """ stop smtp """ self.smtp.quit()
2. Send email
The code is as follows (example):
import multiprocessing # Process module import smtplib from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_mail(send_user, send_pwd, server_url, server_port, to_mail, msg): # msg is the html content object of smtp. MIMEMultipart needs to be used when complex email content needs to be completed. The msg here is MIMEMultipart (complex content is, attachment, tables, pictures, etc.) smtp_send = Smtp(send_user, send_pwd, server_url, server_port) #User name, password, domain name, port smtp_send.mail(to_mail, msg.as_string()) # Recipient’s email address and bytes data (you can also put the string content directly, smtplib will automatically convert it) smtp_send.stop_mail() # After sending the letter, stop the connection
Supplement
After completing the appeal code, you can send emails. However, when sending emails via STMP protocol, it will block the main process and the network. Therefore, when you want to send SMTP protocol emails asynchronously, you cannot achieve asynchronous effects when using threads and coroutines. You need to start a new process.
Attach the complete code and process email
The table style of the mailbox in my code:
import logging import multiprocessing import smtplib from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText error_logger = logging.getLogger('celery-error') class Smtp(object): # Class name customization def __init__(self, sender, pwd, server_url, server_port): """ The username used by sender to log in to the SMTP server. This is usually the sending email address. Note that in addition to using the username and password, you can also use a key. pwd password to log in to the SMTP server server_url SMTP server domain name or IP server_port The port opened by the SMTP service """ self.sender = sender self.smtp = smtplib.SMTP(server_url, server_port, timeout=5) # Create smtp object self.smtp.starttls() # Start TSL encryption self.smtp.login(sender, pwd) # Use password or password to obtain login credentials def mail(self, *args): # Send mail """ The two parameters are: receiving email address and content. """ self.smtp.sendmail(self.sender, args[0], args[1]) def stop_mail(self): # After the email is sent, the connection needs to be closed and resources released. """ stop smtp """ self.smtp.quit() def send_mail(send_user, send_pwd, server_url, server_port, to_mail, msg): # msg is the html content object of smtp. MIMEMultipart needs to be used when complex email content needs to be completed. The msg here is MIMEMultipart (complex content is, attachment, tables, pictures, etc.) smtp_send = Smtp(send_user, send_pwd, server_url, server_port) #User name, password, domain name, port smtp_send.mail(to_mail, msg.as_string()) # Recipient’s email address and bytes data (you can also put the string content directly, smtplib will automatically convert it) smtp_send.stop_mail() # After sending the letter, stop the connection def mail_to_user(**kwargs): user_obj = Users.objects.filter(username=kwargs.get('touser')).first() try: if user_obj: # Recipient’s email address send_user = '[email protected]' #Create a MIMEMultipart object, here I generated a table msg = MIMEMultipart() #Set email subject and sender information msg['From'] = key_obj.accessSecret msg['To'] = send_user msg['Subject'] = Header("Test Email", 'utf-8') # Create a list of table contents table_data = ["Test type", "Test status", "Applicant", "2023-9-26"] #Initialize table HTML string table_html = """ <table> <tr> <th>Type</th> <th>Status</th> <th>Applicant</th> <th>Reservation completion date</th> </tr> """ # Construct the HTML string of the table content. If the content here is multi-line, you can splice this paragraph in a loop. table_html + = f""" <tr> <td>{<!-- -->table_data[0]}</td> <td>{<!-- -->table_data[1]}</td> <td>{<!-- -->table_data[2]}</td> <td>{<!-- -->table_data[3]}</td> </tr> """ table_html + = "</table>" # Add the table content html to the html code html_content = """ <html> <style type="text/css"> table thead, table tr { border-top-width: 1px; border-top-style: solid; border-top-color: rgb(211, 202, 221); } table { border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(211, 202, 221); } table td, table th { padding: 5px 10px; font-size: 12px; font-family: Verdana; color: rgb(95, 74, 121); } table tr:nth-child(even) { background: rgb(223, 216, 232) } table tr:nth-child(odd) { background: #FFF } </style> <body> """ + table_html + """ </body> </html> """ # Add the table content to the email as a MIMEText object table_part = MIMEText(html_content, 'html', 'utf-8') msg.attach(table_part) process = multiprocessing.Process(target=send_mail, args=("[email protected]", "password", "127.0.0.1", 8043, "[email protected]", msg )) process.start() except Exception as e: print(str(e)) error_logger.error('Mail sending error' + str(e))