欢迎访问宙启技术站
智能推送

利用send_mail()函数在Python中发送带有文件链接的邮件

发布时间:2024-01-10 10:29:48

在Python中发送带有文件链接的邮件,可以使用smtplib库中的send_mail()函数。send_mail()函数可以用于发送文本邮件或包含附件的邮件。下面是一个使用例子:

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

def send_mail(sender_email: str, sender_password: str, recipient_email: str, subject: str, message: str, attachment_url: str):
    # 创建一个MIMEMultipart对象作为邮件容器
    msg = MIMEMultipart()

    # 设置发件人、收件人及主题
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject

    # 添加文本内容
    msg.attach(MIMEText(message, 'plain'))

    # 添加附件
    attachment = open(attachment_url, 'rb')
    attach_part = MIMEApplication(attachment.read())
    attach_part.add_header('Content-Disposition', 'attachment', filename=attachment_url.split('/')[-1])
    msg.attach(attach_part)

    # 连接SMTP服务器
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)

    # 发送邮件
    server.sendmail(sender_email, recipient_email, msg.as_string())

    # 断开连接
    server.quit()

# 使用例子
sender_email = 'sender@gmail.com'
sender_password = 'password'
recipient_email = 'recipient@gmail.com'
subject = 'Test Subject'
message = 'This is a test email with an attachment.'
attachment_url = 'https://example.com/file.pdf'

send_mail(sender_email, sender_password, recipient_email, subject, message, attachment_url)

在这个例子中,我们首先导入了所需的库,然后定义了一个send_mail()函数来发送邮件。该函数接受发送者的邮箱地址、密码,接收者的邮箱地址,邮件的主题、文本内容以及附件的链接作为参数。

在send_mail()函数内部,我们首先创建了一个MIMEMultipart对象作为邮件容器。然后设置发件人、收件人和主题。接下来,我们将文本内容添加到邮件中,并以纯文本格式进行附加。

然后,我们打开附件文件,并以二进制方式读取其内容。我们创建一个MIMEApplication对象,并将附件内容设置为附件对象的内容。我们还通过设置Content-Disposition标头指定附件的文件名,并将附件对象添加到邮件容器中。

接下来,我们连接到SMTP服务器,并使用提供的邮箱地址和密码进行登录。

最后,我们使用sendmail()方法将邮件发送给收件人。

在使用例子中,我们定义了发送者的邮箱地址、密码,以及收件人的邮箱地址、主题、内容和附件的链接。然后我们调用send_mail()函数来发送邮件。

请确保在使用这个例子之前,你已经安装了smtplib库,并将smtp服务器设置为你要使用的电子邮件提供商的smtp服务器。同时,需要注意在使用实际的邮箱密码时应使用安全措施,例如使用环境变量来存储密码,并在代码中引用该变量。