首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用Python 3.6发送电子邮件附件

使用Python 3.6发送电子邮件附件可以通过使用内置的smtplib和email库来实现。下面是一个完整的示例代码:

代码语言:python
代码运行次数:0
复制
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
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):
    # 创建一个带附件的邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

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

    # 添加附件
    attachment = open(attachment_path, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', f"attachment; filename= {attachment_path}")
    msg.attach(part)

    # 发送邮件
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login(sender_email, sender_password)
        server.send_message(msg)

# 使用示例
sender_email = "your_email@gmail.com"
sender_password = "your_password"
receiver_email = "recipient_email@example.com"
subject = "Sample Email with Attachment"
message = "This is a sample email with attachment."
attachment_path = "path_to_attachment_file"

send_email_with_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path)

上述代码中,需要替换以下变量的值:

  • sender_email: 发件人的邮箱地址
  • sender_password: 发件人的邮箱密码
  • receiver_email: 收件人的邮箱地址
  • subject: 邮件主题
  • message: 邮件正文内容
  • attachment_path: 附件文件的路径

这段代码使用Gmail的SMTP服务器发送邮件,如果你使用其他邮箱提供商,请相应地更改SMTP服务器的地址和端口号。

推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/etp

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券