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

Python从函数向电子邮件添加附件

的方法可以通过使用Python的内置模块smtplib和email来实现。下面是一个完整的示例代码:

代码语言:txt
复制
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', "attachment; filename= %s" % attachment_path)
    msg.attach(part)

    # 发送邮件
    server = smtplib.SMTP('smtp.example.com', 587)  # 替换为你的SMTP服务器地址和端口
    server.starttls()
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
    server.quit()

# 使用示例
sender_email = "your_email@example.com"
sender_password = "your_password"
receiver_email = "recipient@example.com"
subject = "Email with Attachment"
message = "Please see the attached file."
attachment_path = "path_to_attachment_file"

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

上述代码中,我们首先导入了需要的模块,然后定义了一个名为send_email_with_attachment的函数,该函数接受发送者邮箱、发送者密码、接收者邮箱、主题、消息内容和附件路径作为参数。

在函数内部,我们创建了一个MIMEMultipart对象来表示带附件的邮件。然后,我们设置邮件的发送者、接收者和主题,并将消息内容添加到邮件中。

接下来,我们打开附件文件,并将其添加到邮件中。我们使用MIMEBase对象来表示附件,并使用encoders模块对附件进行编码。最后,我们将附件添加到邮件中。

最后,我们使用SMTP服务器发送邮件。我们需要替换代码中的SMTP服务器地址和端口,以及发送者邮箱和密码。然后,我们调用sendmail方法将邮件发送给接收者,并在发送完成后关闭SMTP连接。

这是一个简单的示例,你可以根据自己的需求进行修改和扩展。如果你想了解更多关于Python发送电子邮件的知识,可以参考腾讯云的Python发送邮件文档。

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

相关·内容

领券