In Python programming, sending emails is a common requirement, whether it is for automated reporting, user notifications, or simple exchange of information. With its simple API and powerful features, the yagmail library has become the preferred tool for many developers to send emails.
1. Introduction to yagmail
1.1 What is yagmail
yagmail is a Python library designed to simplify the process of sending emails over the SMTP protocol. It encapsulates the underlying SMTP connection details and provides an intuitive interface that allows developers to implement email sending functions with minimal code.
1.2 Main features
Ease of use: A minimalist API design, sending emails in just a few lines of code.
Security: Supports SSL/TLS encryption to protect email data.
Attachment support: Easily attach files, including pictures, PDFs, etc.
HTML mail: Supports HTML format email content to improve email expression.
Multi-recipients: Supports single or multiple recipients, as well as CC (CC) and BCC (secret delivery).
1.3 Key parameters
Parameter name | describe | Example Values |
---|---|---|
user | Email account for sending email | 'your_email@' |
password | Login password or authorization code of the email address (Note: hard-coded passwords in the code are not recommended, and environment variables or configuration file storage is recommended) | 'your_password_or_auth_code' |
host | SMTP server address varies according to the email service provider (for example, QQ mailbox is '’) | '' |
port | The SMTP server port defaults to 25, but for security reasons, encrypted ports such as 465 or 587 are often used. | 465 or 587 |
ssl | Whether to use SSL encrypted connections, usually used with port 465 | True/False |
starttls | Whether to enable STARTTLS encryption (for servers that support STARTTLS), it is usually used with port 587 | True/False |
to | The recipient's email address can be a string or a list of strings (supports multiple recipients) | 'recipient@' or ['recipient1@', 'recipient2@'] |
subject | The subject of the email | 'Email Subject' |
contents | The text content of the message can be a string, HTML, or a list containing attachments. | 'Mail content' or '<h1>HTML mail</h1>' or ['Body 1', 'Body 2'] (usually used for multipart mail when it is a list) |
attachments | The path to the attachment can be a string or a list of paths (supports multiple attachments) | '/path/to/' or ['/path/to/', '/path/to/'] |
cc | Cc email address list, send the email to people other than the recipient at the same time | ['cc_recipient1@', 'cc_recipient2@'] |
bcc | The address list of the emails that are sent to the cc is that the recipient cannot see the email address of others | ['bcc_recipient1@', 'bcc_recipient2@'] |
headers | Customize email header information, pass dictionary parameters | {'Reply-To': 'noreply@', 'X-Priority': '1'} |
preview_only | Boolean, which means that the email is only previewed and not actually sent. It can be used to test whether the email content is correct. | True/False |
from_ | Specify the sender's email address (note: the underscore is part of the parameter name, not a typo) | 'another_email@' (used to disguise the sender's address, but pay attention to the policies of the email service provider) |
debug | Whether to enable debugging mode and output more log information will help troubleshoot problems during email sending | True/False |
2. Install yagmail
2.1 Installation method
yagmail can be installed through Python's package management tool pip. Run the following command on the command line:
pip install yagmail
2.2 Dependencies
yagmail relies on smtplib (part of the Python standard library) and requests libraries to handle HTTP requests (mainly used to verify certain mail services).
3. Basic usage
3.1 Configuring the SMTP server
Before sending emails, you need to configure the information of the SMTP server, including the server address, port, username, and password.
3.2 Send simple text emails
Here is an example of sending simple text messages:
import yagmail # Connect to the SMTP serveryag = ('your_email@', 'your_password') # Send email('recipient@', 'Subject', 'This is the body of the email.')
3.3 Send HTML mail
yagmail also supports sending HTML-formatted mail:
# Send HTML mail('recipient@', 'Subject', contents=['<h1>Hello World!</h1>'])
4. Advanced functions
4.1 Add attachments
yagmail allows you to easily add attachments:
# Send emails with attachments('recipient@', 'Subject', 'Here is your report.', attachments=['path/to/'])
4.2 Multi-recipient processing
You can send emails to multiple recipients at the same time, or you can set up cc and passport:
# Multiple recipientsrecipients = ['user1@', 'user2@'] (recipients, 'Subject', 'Message for multiple recipients.') # cc and secret('user1@', 'Subject', 'Message', cc=['user2@'], bcc=['user3@'])
4.3 Custom email header
You can customize email header information, such as reply address, priority, etc.:
# Customize email header('recipient@', 'Subject', 'Message', headers={'Reply-To': 'noreply@', 'X-Priority': '1'})
5. Error handling and debugging
5.1 Common Errors
Authentication failed: Check whether the username and password are correct.
SMTP connection error: Confirm that the SMTP server address and port are correct, and the server allows your IP address to connect.
Attachment sending failed: Make sure the attachment path is correct and the file is readable.
5.2 Debugging skills
Turn on debug mode: Turn on debug mode through debug parameters to obtain more log information during the sending process.
Check the email log: Check the mail server's log to see if the email has been successfully received or rejected.
6. Best Practices
6.1 Security
Environment variables: Avoid hard-code sensitive information in the code, such as mailbox passwords, and it is recommended to use environment variables or configuration file storage.
OAuth2 authentication: For mail services that support OAuth2 (such as Gmail), use OAuth2 token instead of password for authentication to improve security.
6.2 Performance optimization
Batch Send: If you need to send a large amount of email, consider using batch send or batch sending to reduce server stress.
Asynchronous processing: For email sending tasks that require low real-time requirements, an asynchronous programming model can be used to improve program response speed.
7. Example demonstration: Send HTML mail with attachments
7.1 Code Example
import yagmail # Connect to the SMTP serveryag = ('your_email@', 'your_password') # Email contentsubject = 'Monthly Report' body = ''' <h1>Monthly Sales Report</h1> <p>Please find the attached report for the month of October.</p> ''' attachments = ['/path/to/'] # Send email('recipient@', subject, body, attachments=attachments)
7.2 Summary of key points
SMTP configuration: correctly configure SMTP server information.
Mail format: Use HTML format to enhance mail readability.
Attachment processing: Ensure that the attachment path is correct and the file type is supported.
8. Summary
With its simple API and rich features, yagmail provides Python developers with an efficient and secure mail delivery solution. Whether it is simple text email or complex HTML email and attachments, yagmail can easily deal with it.
This is the end of this article about Python using yagmail to achieve automated email marketing. For more related Python yagmail email marketing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!