如何使用Python自动发送邮件?

Python 提供了强大的内置库 smtplib 和 email,让我们能够轻松地发送各种类型的电子邮件。本指南将带你逐步了解如何使用 Python 发送邮件,从简单文本邮件到包含 HTML 内容、附件和内嵌图片的复杂邮件。

1. 准备工作:

1.1 安装必要的库

确保你的 Python 环境中安装了 smtplib 和 email 库。如果未安装,可以使用 pip 进行安装:

 
pip install smtplib email

1.2 启用第三方应用访问权限

许多邮箱服务商 (如 Gmail) 默认情况下会阻止第三方应用访问。你需要在邮箱设置中启用第三方应用访问权限,或者生成应用专用密码 (授权码)。

2. 发送简单文本邮件

让我们从最简单的文本邮件开始。以下是使用 smtplib 和 email.mime.text 发送文本邮件的代码示例:

import smtplib
from email.mime.text import MIMEText

def send_plain_email(sender_email, sender_password, receiver_email, subject, message):
  """发送简单文本邮件。

  Args:
    sender_email: 发送方邮箱地址。
    sender_password: 发送方邮箱密码 (或授权码)。
    receiver_email: 接收方邮箱地址。
    subject: 邮件主题。
    message: 邮件内容。
  """
  msg = MIMEText(message, 'plain', 'utf-8')
  msg['Subject'] = subject
  msg['From'] = sender_email
  msg['To'] = receiver_email

  try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
      server.login(sender_email, sender_password)
      server.send_message(msg)
    print("邮件发送成功!")
  except Exception as e:
    print(f"邮件发送失败:{e}")

# 示例用法
send_plain_email("your_email@gmail.com", "your_password", "recipient@example.com", "测试邮件", "这是一封测试邮件。")

代码解释:

  1. 导入库: 导入 smtplib 和 email.mime.text。

  2. 定义函数 send_plain_email: 该函数接收发送方邮箱、密码、接收方邮箱、主题和内容作为参数,用于发送邮件。

  3. 创建邮件内容: 使用 MIMEText(message, 'plain', 'utf-8') 创建一个文本邮件对象 msg, 并设置主题、发件人和收件人。

  4. 发送邮件:

    • 使用 smtplib.SMTP_SSL() 连接到 Gmail 的 SMTP 服务器 (smtp.gmail.com, 端口号 465)。

    • 使用 server.login() 登录你的邮箱账号。

    • 使用 server.send_message() 发送邮件。

3. 发送 HTML 格式邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_html_email(sender_email, sender_password, receiver_email, subject, html_content):
  """发送 HTML 格式的邮件。

  Args:
    sender_email: 发送方邮箱地址。
    sender_password: 发送方邮箱密码 (或授权码)。
    receiver_email: 接收方邮箱地址。
    subject: 邮件主题。
    html_content: 邮件 HTML 内容。
  """
  msg = MIMEMultipart('alternative')  # 创建多部分邮件
  msg['Subject'] = subject
  msg['From'] = sender_email
  msg['To'] = receiver_email

  # 添加 HTML 部分
  part = MIMEText(html_content, 'html', 'utf-8')
  msg.attach(part)

  # 发送邮件
  try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
      server.login(sender_email, sender_password)
      server.send_message(msg)
    print("邮件发送成功!")
  except Exception as e:
    print(f"邮件发送失败:{e}")

# 示例用法
html_content = """
<html>
  <head></head>
  <body>
    <p>这是一封<b>HTML</b>格式的邮件,包含图片和链接:</p>
    <img src="cid:image1" alt="图片">
    <p><a href="https://www.example.com">这是一个链接</a></p>
  </body>
</html>
"""

send_html_email("your_email@gmail.com", "your_password", "recipient@example.com", "HTML 邮件测试", html_content)

要点:

  • 使用 MIMEMultipart('alternative') 创建多部分邮件,以支持纯文本和 HTML 两种格式。

  • 使用 MIMEText(html_content, 'html', 'utf-8') 创建 HTML 格式的邮件内容。

4. 发送带附件的邮件

你可以使用 email.mime.base.MIMEBase 和 email.encoders 模块发送带附件的邮件:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path):
  """发送带附件的邮件。

  Args:
    sender_email: 发送方邮箱地址。
    sender_password: 发送方邮箱密码 (或授权码)。
    receiver_email: 接收方邮箱地址。
    subject: 邮件主题。
    message: 邮件内容。
    attachment_path: 附件文件路径。
  """
  msg = MIMEMultipart()
  msg['Subject'] = subject
  msg['From'] = sender_email
  msg['To'] = receiver_email

  # 添加邮件正文
  msg.attach(MIMEText(message, 'plain', 'utf-8'))

  # 添加附件
  with open(attachment_path, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())
  encoders.encode_base64(part)  # 对附件进行 base64 编码
  part.add_header(
    "Content-Disposition",
    f"attachment; filename= {attachment_path}",
  )
  msg.attach(part)

  # 发送邮件
  try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
      server.login(sender_email, sender_password)
      server.send_message(msg)
    print("邮件发送成功!")
  except Exception as e:
    print(f"邮件发送失败:{e}")

# 示例用法
send_email_with_attachment("your_email@gmail.com", "your_password", "recipient@example.com", "附件测试", "这是一封带附件的邮件。", "/path/to/your/attachment.pdf")

要点:

  • 使用 MIMEBase("application", "octet-stream") 创建附件部分。

  • 使用 encoders.encode_base64(part) 对附件进行 base64 编码,确保能够通过邮件发送。

  • 使用 part.add_header("Content-Disposition", f"attachment; filename= {attachment_path}") 设置附件的文件名。

5. 发送内嵌图片的 HTML 邮件

为了在邮件正文中直接显示图片,可以使用内嵌图片:

python
复制代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def send_html_email_with_embedded_image(sender_email, sender_password, receiver_email, subject, html_content, image_path):
  """发送包含内嵌图片的 HTML 邮件。

  Args:
    sender_email: 发送方邮箱地址。
    sender_password: 发送方邮箱密码 (或授权码)。
    receiver_email: 接收方邮箱地址。
    subject: 邮件主题。
    html_content: 邮件 HTML 内容。
    image_path: 图片路径。
  """
  msg = MIMEMultipart('related')
  msg['Subject'] = subject
  msg['From'] = sender_email
  msg['To'] = receiver_email

  # 创建 HTML 部分
  msg_alternative = MIMEMultipart('alternative')
  msg.attach(msg_alternative)
  part = MIMEText(html_content, 'html', 'utf-8')
  msg_alternative.attach(part)

  # 添加内嵌图片
  with open(image_path, 'rb') as f:
    img = MIMEImage(f.read())
  img.add_header('Content-ID', '<image1>') # 设置图片 ID
  img.add_header('Content-Disposition', 'inline')
  msg.attach(img)

  # 发送邮件
  try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
      server.login(sender_email, sender_password)
      server.send_message(msg)
    print("邮件发送成功!")
  except Exception as e:
    print(f"邮件发送失败:{e}")

# 示例用法
html_content = """
<html>
  <head></head>
  <body>
    <p>这是一封包含<b>内嵌图片</b>的邮件:</p>
    <img src="cid:image1" alt="图片">
  </body>
</html>
"""

send_html_email_with_embedded_image("your_email@gmail.com", "your_password", "recipient@example.com", "内嵌图片测试", html_content, "/path/to/your/image.jpg")

要点:

  • 使用 MIMEMultipart('related') 创建多部分邮件,用于关联内嵌图片和 HTML 内容。

  • 使用 MIMEImage(f.read()) 创建图片部分。

  • 使用 img.add_header('Content-ID', '<image1>') 为图片设置 ID,并在 HTML 代码中使用 cid:image1 引用该 ID。

6. 总结

本指南介绍了使用 Python 发送各种类型邮件的基本方法,包括简单文本邮件、HTML 邮件、带附件的邮件以及包含内嵌图片的邮件。你可以根据自己的需求选择合适的方法,并根据实际情况修改代码示例。

到这里所有的教程都已经完成了,如果对你有帮助,记得点赞分享支持一下~

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

途途途途

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值