In daily work and life, we often need to send emails, such as batch notifications, marketing promotion, automatic daily reports, server alerts, etc. Sending emails manually is not only cumbersome, but also prone to errors. Fortunately, Python provides powerful smtplib and email modules, which can automatically send emails, whether they are plain text messages or emails with attachments and HTML formats, they can be easily handled. This article will introduce in detail how to use Python to send emails in batches, add attachments, and send HTML mail, and combine schedule to realize scheduled mail sending, making your work smarter and more efficient.
1. Environmental preparation and basic operation
1. Install the necessary libraries
Python comes with smtplib and email modules without additional installation, but if you need to send emails regularly, you can install the schedule library. The installation command is as follows:
pip install schedule
2. Configure the email
Taking QQ mailbox as an example, after logging in to QQ mailbox, find the "Account" option in the settings, enable the POP3/SMTP service, and obtain the authorization code (used instead of password). The configuration process of other mailboxes is similar. Generally, it is necessary to enable SMTP service and generate an authorization code.
3. Send simple emails
Here is a sample code for sending simple text messages:
import smtplib from import MIMEText def send_email(subject, content, to_addr): # Email Configuration from_addr = 'your_email@' password = 'your_authorization_code' # Authorization code # Create email content msg = MIMEText(content, 'plain', 'utf-8') msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject # Send email try: server = smtplib.SMTP_SSL('', 465) (from_addr, password) (from_addr, [to_addr], msg.as_string()) () print("Email sent successfully") except Exception as e: print(f"Email sending failed:{str(e)}") #User Examplesend_email('Test email', 'This is a test email', 'recipient@')
In this code, we first import the necessary libraries and then define the send_email function to send emails. Inside the function, we set the sender email, authorization code, and recipient email, and create the email content. Next, we use the SMTP server to send the mail and handle possible exceptions.
2. Advanced processing of email content
1. Send HTML format emails
HTML-formatted emails can contain hyperlinks, images and custom styles to make the email content more beautiful. Here is a sample code for sending HTML-formatted mail:
from import MIMEText def send_html_email(subject, html_content, to_addr): from_addr = 'your_email@' password = 'your_authorization_code' msg = MIMEText(html_content, 'html', 'utf-8') msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject try: server = smtplib.SMTP_SSL('', 465) (from_addr, password) (from_addr, [to_addr], msg.as_string()) () print("Email sent successfully") except Exception as e: print(f"Email sending failed:{str(e)}") #User Examplehtml_content = """ <h1>Monthly Report</h1> <p>The following are the main data for this month:</p> <ul> <li>Sales: ¥120,000</li> <li>New customers: 15</li> <li>Customer satisfaction: 95%</li> </ul> """ send_html_email('Monthly Report', html_content, 'manager@')
In this code, we just need to set the email content to a string in HTML format and set the second parameter of MIMEText to 'html'.
2. Use templates to generate email content
To simplify the writing of email content, we can use templates to generate email content. Here is a sample code that uses templates to generate HTML mail content:
from string import Template from import MIMEText def generate_email_content(template_file, data): with open(template_file, 'r', encoding='utf-8') as file: template = Template(()) return (data) #Template file example()""" <h1>${title}</h1> <p>Honey${name}:</p> <p>${content}</p> <p>expiration date:${deadline}</p> """ #User Exampledata = { 'title': 'Project progress reminder', 'name': 'Manager Zhang', 'content': 'Please submit the project progress report in time', 'deadline': '2023-10-15' } html_content = generate_email_content('', data) send_html_email('Project Reminder', html_content, 'manager@')
In this code, we first define the generate_email_content function, which is used to read the template from the template file and replace the placeholder in the template with the provided data. Then, we use the sample data and template files to generate HTML mail content and call the send_html_email function to send the mail.
3. Processing of email attachments
1. Add a single attachment
When sending emails, we sometimes need to add attachments, such as PDF, Excel, pictures, etc. Here is a sample code for adding a single attachment:
from import MIMEMultipart from import MIMEBase from email import encoders def send_email_with_attachment(subject, content, to_addr, attachment_path): from_addr = 'your_email@' password = 'your_authorization_code' msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject # Add text (MIMEText(content, 'plain', 'utf-8')) # Add attachment with open(attachment_path, 'rb') as file: part = MIMEBase('application', 'octet-stream') part.set_payload(()) encoders.encode_base64(part) part.add_header('Content-Disposition', f'attachment; filename={attachment_path}') (part) try: server = smtplib.SMTP_SSL('', 465) (from_addr, password) (from_addr, [to_addr], msg.as_string()) () print("The email was sent successfully, the attachment was already included!") except Exception as e: print(f"Email sending failed:{str(e)}") #User Examplesend_email_with_attachment('Email with attachment', 'Please check the attachment', 'recipient@', 'monthly_report.pdf')
In this code, we use the MIMEMultipart object to create the message and use the MIMEBase and encoders modules to add attachments. Note that when adding attachments, we need to open the attachment file in binary mode and read its contents.
2. Add attachments in batches
If you need to add attachments in batches, we can make simple modifications to the above code. Here is a sample code for batch adding attachments:
def send_email_with_attachments(subject, content, to_addr, attachment_paths): from_addr = 'your_email@' password = 'your_authorization_code' msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject # Add text (MIMEText(content, 'plain', 'utf-8')) # Add multiple attachments for path in attachment_paths: with open(path, 'rb') as file: part = MIMEBase('application', 'octet-stream') part.set_payload(()) encoders.encode_base64(part) part.add_header('Content-Disposition', f'attachment; filename={path}') (part) try: server = smtplib.SMTP_SSL('', 465) (from_addr, password) (from_addr, [to_addr], msg.as_string()) () print("The email was sent successfully, multiple attachments were included!") except Exception as e: print(f"Email sending failed:{str(e)}") #Usage Exampleattachment_paths = ['', '', ''] send_email_with_attachments('Email with multiple attachments', 'Please check all attachments', 'recipient@', attachment_paths)
In this code, we just need to iterate over the attachment_paths list and perform the same addition steps for each attachment.
4. Combining scheduled mail delivery
Using the schedule library, we can easily implement scheduled mail delivery. Here is a sample code that combines scheduled sending timed mail:
import schedule import time #Function of sending emails regularlydef scheduled_email(): subject = 'Timely reminder' content = 'This is a timely email' to_addr = 'recipient@' send_email(subject, content, to_addr) #Set emails every day at 9 am().("09:00").do(scheduled_email) #Keep the script running, check and execute timing taskswhile True: schedule.run_pending() (1)
In this code, we first define the scheduled_email function, which calls the previously defined send_email function to send email. Then, we use().("09:00").do(scheduled_email) to set the scheduled_email function to be executed at 9 am every day. Finally, we use an infinite loop to keep the script running and constantly check if there are timed tasks to be executed.
Note: In practical applications, it may not be best practice to directly run scripts in an infinite loop. You might consider using the operating system's scheduled task features (such as Windows' task scheduler or Linux's cron jobs) to run Python scripts regularly.
5. Summary
Through this article, we learned how to use Python's smtplib and email modules to send simple emails, HTML format emails, and emails with attachments, and combined with the schedule library to realize timed email sending. These tips can greatly improve your work efficiency and reduce the cumbersomeness and error rate of sending emails manually. Whether it is daily notifications, marketing promotion, daily report sending or server alerts, Python can help you easily handle it.
This is the end of this article about Python's detailed explanation of batch email automation. For more related Python email automation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!