在日常工作和项目中,邮件自动化是提高效率的关键环节之一。Python的yagmail库提供了一种简单且强大的方式来实现邮件发送自动化。本文将详细介绍yagmail库的功能、安装与配置、基本和高级用法,以及如何在实际项目中应用它。
yagmail(Yet Another Gmail/SMTP client)是一个基于Python的邮件发送库,旨在简化通过SMTP发送电子邮件的过程。它支持富文本邮件、多附件、嵌入图片等功能,使得邮件发送变得轻松便捷。yagmail特别适用于自动化脚本和定时任务中的邮件发送需求。
使用pip可以轻松安装yagmail库:
- pip install yagmail
在首次使用yagmail发送邮件前,需要进行SMTP服务器的配置。以Gmail为例,首先需要在Gmail账户中启用"低安全性应用"访问权限。
使用yagmail发送一封简单的邮件:
- import yagmail
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 发送邮件
- yag.send(
- to='recipient_email@gmail.com',
- subject='Test Email',
- contents='This is a test email sent using yagmail.'
- )
- print("Email sent successfully.")
发送一封带有附件的邮件:
- import yagmail
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 发送邮件
- yag.send(
- to='recipient_email@gmail.com',
- subject='Test Email with Attachment',
- contents='This email contains an attachment.',
- attachments='path/to/your/file.txt'
- )
- print("Email with attachment sent successfully.")
发送一封HTML格式的邮件:
- import yagmail
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 发送邮件
- html_content = """
- <h1>This is a test email</h1>
- <p>This email is sent using <b>yagmail</b> and contains <i>HTML</i> content.</p>
- """
- yag.send(
- to='recipient_email@gmail.com',
- subject='Test HTML Email',
- contents=html_content
- )
- print("HTML email sent successfully.")
在邮件正文中嵌入图片:
- import yagmail
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 发送邮件
- html_content = """
- <h1>Embedded Image</h1>
- <img src="cid:image1">
- """
- yag.send(
- to='recipient_email@gmail.com',
- subject='Email with Embedded Image',
- contents=html_content,
- attachments=['path/to/your/image.jpg']
- )
- print("Email with embedded image sent successfully.")
实现批量邮件发送:
- import yagmail
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 收件人列表
- recipients = ['recipient1@gmail.com', 'recipient2@gmail.com', 'recipient3@gmail.com']
-
- # 发送邮件
- for recipient in recipients:
- yag.send(
- to=recipient,
- subject='Batch Email',
- contents='This is a batch email sent to multiple recipients.'
- )
- print("Batch emails sent successfully.")
发送邮件并处理回复和转发:
- import yagmail
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 发送邮件
- original_email = yag.send(
- to='recipient_email@gmail.com',
- subject='Email with Reply-To',
- contents='This email has a reply-to address.',
- reply_to='reply_to_email@gmail.com'
- )
- print("Email sent successfully.")
-
- # 转发邮件
- yag.forward(
- original_email,
- to='another_recipient@gmail.com',
- subject='Fwd: Email with Reply-To',
- contents='Forwarding the previous email.'
- )
- print("Email forwarded successfully.")
使用yagmail实现自动发送报告的功能:
- import yagmail
- import datetime
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 生成报告
- report_date = datetime.date.today().strftime('%Y-%m-%d')
- report_file = f'report_{report_date}.pdf'
-
- # 发送报告邮件
- yag.send(
- to='recipient_email@gmail.com',
- subject=f'Daily Report - {report_date}',
- contents=f'Please find attached the daily report for {report_date}.',
- attachments=report_file
- )
- print("Daily report sent successfully.")
使用yagmail实现邮件通知系统:
- import yagmail
- import os
-
- # 初始化yagmail客户端
- yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
-
- # 监控文件夹
- folder_to_monitor = 'path/to/your/folder'
-
- # 发送通知邮件
- def send_notification(file_name):
- yag.send(
- to='recipient_email@gmail.com',
- subject='New File Alert',
- contents=f'A new file named {file_name} has been added to the monitored folder.',
- attachments=os.path.join(folder_to_monitor, file_name)
- )
- print(f'Notification for {file_name} sent successfully.')
-
- # 检查文件夹变化
- def monitor_folder():
- monitored_files = set(os.listdir(folder_to_monitor))
- while True:
- current_files = set(os.listdir(folder_to_monitor))
- new_files = current_files - monitored_files
- if new_files:
- for new_file in new_files:
- send_notification(new_file)
- monitored_files = current_files
-
- # 开始监控
- monitor_folder()
yagmail库是Python邮件自动化领域的一个强大工具,能够轻松实现邮件发送、带附件邮件、嵌入图片邮件以及批量邮件发送等功能。通过结合SMTP服务器配置,yagmail提供了简洁易用的API,使得邮件自动化变得更加便捷和高效。本文详细介绍了yagmail的安装与配置、核心功能、基本和高级用法,并通过实际应用案例展示了其在自动发送报告和邮件通知系统中的应用。希望本文能帮助大家更好地理解和使用yagmail库,在项目中充分利用其强大功能,提高邮件自动化的效率。