yagmail
是一个用于发送电子邮件的 Python 库,它简化了发送邮件的过程,特别适合用于自动化任务。yagmail
的 send
方法是其核心功能之一,用于发送电子邮件。下面是对 send
方法的详细讲解。
1. 安装 yagmail
首先,你需要安装 yagmail
库。可以通过以下命令安装:
pip install yagmail
2. 初始化 yagmail
在使用 send
方法之前,你需要初始化 yagmail
。通常你需要提供发件人的邮箱地址和密码(或应用专用密码)。
import yagmail
# 初始化 yagmail
yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
3. send 方法的基本用法
send
方法用于发送邮件。它的基本语法如下:
yag.send(to, subject, contents)
to
: 收件人的邮箱地址,可以是字符串或列表。subject
: 邮件的主题。contents
: 邮件的内容,可以是字符串、列表或字典。
示例 1: 发送简单的文本邮件
yag.send('recipient@example.com', 'Subject', 'This is the body of the email.')
示例 2: 发送带有附件的邮件
yag.send(
to='recipient@example.com',
subject='Subject',
contents='This is the body of the email.',
attachments=['/path/to/attachment.txt']
)
4. contents 参数的详细说明
contents
参数可以是多种形式:
- 字符串: 直接作为邮件正文。
- 列表: 列表中的每个元素可以是字符串或附件路径。
- 字典: 可以指定 HTML 内容、纯文本内容等。
示例 3: 使用列表作为 contents
yag.send(
to='recipient@example.com',
subject='Subject',
contents=['This is the body of the email.', '/path/to/attachment.txt']
)
示例 4: 使用字典作为 contents
yag.send(
to='recipient@example.com',
subject='Subject',
contents={
'text': 'This is the plain text body.',
'html': '<h1>This is the HTML body</h1>',
'attachments': ['/path/to/attachment.txt']
}
)
5. 其他可选参数
send
方法还支持其他可选参数,例如:
cc
: 抄送地址。bcc
: 密送地址。headers
: 自定义邮件头。preview_only
: 如果设置为True
,则只打印邮件内容而不发送。
示例 5: 使用 cc 和 bcc
yag.send(
to='recipient@example.com',
cc='cc@example.com',
bcc='bcc@example.com',
subject='Subject',
contents='This is the body of the email.'
)
6. 关闭连接
发送完邮件后,可以关闭 yagmail
的连接:
yag.close()
7. 完整示例
import yagmail
# 初始化 yagmail
yag = yagmail.SMTP('your_email@gmail.com', 'your_password')
# 发送邮件
yag.send(
to='recipient@example.com',
subject='Subject',
contents=['This is the body of the email.', '/path/to/attachment.txt'],
cc='cc@example.com',
bcc='bcc@example.com'
)
# 关闭连接
yag.close()
总结
yagmail
的 send
方法非常灵活,支持多种形式的邮件内容和附件。通过合理使用 contents
参数和其他可选参数,你可以轻松地发送各种类型的电子邮件。