SoFunction
Updated on 2025-04-14

Python uses Yagmail library to implement automated email marketing

1. Introduction to Yagmail

Yagmail is a Python library for sending emails designed to make the process of sending emails as simple as possible. With a few lines of code, you can send mail with attachments without digging into the complexity of the SMTP protocol. In addition, Yagmail also provides many convenient features, such as saving user credentials, so you don’t have to enter your username and password every time you send an email.

2. Install Yagmail

Before you start using Yagmail, you need to install this library first. You can install it through Python's package management tool pip. Run the following command on the command line:

pip install yagmail

Once the installation is complete, you can start sending emails using Yagmail.

3. Basic usage examples

1. 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.')

In this example, we first imported the yagmail module and created a Yagmail client instance using the SMTP method. When creating an instance, you need to provide the sender's email address and password. Then, we define the subject and content of the email and send the email through the send method.

2. Send HTML mail

Yagmail also supports sending HTML-formatted mail:

# Send HTML mail('recipient@', 'Subject', contents=['<h1>Hello World!</h1>'])

3. Send emails with attachments

Yagmail allows you to easily add attachments:

# Send emails with attachments('recipient@', 'Subject', 'Here is your report.', attachments=['path/to/'])

4. Multiple 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@'])

5. Customize the 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'})

4. Advanced functions

1. SMTP configuration

Before sending emails, you need to configure the information of the SMTP server, including the server address, port, username and password. For example, if you are using QQ mailbox, you need to enable the SMTP service and obtain the authorization code. The configuration is as follows:

def send_yagmail(sender, send_password, addressee, host='', port=465):
    yag = (sender, send_password, host, port)
    # The logic of sending emails    (addressee, 'Subject', 'This is a test email.')
    ()

2. Email Template

Yagmail can create email templates to make it easier to generate similarly structured emails. Here is an example showing how to use a template:

import yagmail
 
# Configure sender's credentialsemail_address = "your_email@"
email_password = "your_password"
 
# Create a yagmail clientyag = (email_address, email_password)
 
# Define templatestemplate = """
Hello, {name}! This is a personalized email.
Best regards,
Your Name
"""
 
# Send email using templateto = "recipient@"
subject = "Personalized Email"
contents = (name="Recipient Name")
(to, subject, contents)
 
# Close the yagmail client()

3. OAuth2 certification

For mail services that support OAuth2 (such as Gmail), you can use OAuth2 token instead of password for authentication to improve security. Here is an example using OAuth2 authentication:

import yagmail
 
# Configure OAuth2 credentialsemail_address = "your_email@"
oauth2_file = "path/to/oauth2_file.json"
 
# Create a yagmail clientyag = (email_address, oauth2_file=oauth2_file)
 
# Send an emailto = "recipient@"
subject = "OAuth2 Example"
contents = "This email is sent using OAuth2 authentication."
(to, subject, contents)
 
# Close the yagmail client()

5. Automated email marketing cases

Suppose you need to send marketing emails to a group of potential customers, with a product introduction PDF. Here is a complete example of automated email marketing:

import yagmail
 
# Configure sender's credentialsemail_address = "your_email@"
email_password = "your_password"
 
# Create a yagmail clientyag = (email_address, email_password)
 
# Recipient listrecipients = [
    'user1@',
    'user2@',
    # ... More Recipients]
 
# Email Subject and Contentsubject = "Product Introduction"
body = """
<h1>Welcome to Our Product</h1>
<p>Please find the attached product introduction PDF for more details.</p>
"""
 
# Attachment pathattachment = 'path/to/product_introduction.pdf'
 
# Send emailfor recipient in recipients:
    (recipient, subject, body, attachments=[attachment])
 
# Close the yagmail client()

In this example, we first configure the sender's credentials and create the Yagmail client. We then define a list of recipients, as well as the subject and content of the email. Finally, we iterate through the recipient list and send emails one by one.

6. Error handling and debugging

You may encounter some common errors when using Yagmail for mailing. Here are some suggestions for error handling:

  • 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.

In order to obtain more log information during the sending process, you can enable debug mode through Yagmail's debug parameters:

yag = ('your_email@', 'your_password', debug=True)

7. Best Practices

  • 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.
  • 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.

8. Summary

With its simple API and rich features, Yagmail provides Python developers with an efficient and secure email sending solution. Whether it is simple text email or complex HTML email and attachments, Yagmail can handle it easily. Through the introduction of this article, I believe you have mastered the methods of using Yagmail to achieve automated email marketing. Hopefully these knowledge and skills can help you achieve better results in the field of digital marketing.

The above is the detailed content of Python using the Yagmail library to achieve automated email marketing. For more information about Python Yagmail email marketing, please follow my other related articles!