您的位置:

Python发送邮件示例

Python是一种多功能的编程语言,可以用于Web开发、自动化、数据分析等多种应用。在应用Python编写邮件时,可以利用Python内置的smtplib模块以及email模块来发送电子邮件。这些模块提供了可靠、方便的方法,使得Python成为一个广泛用于发送自动邮件的工具。

一、发送纯文本电子邮件

发送纯文本邮件非常简单,只需使用Python内置的smtplib和email模块。以下是纯文本电子邮件发送代码示例:

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('这是一封纯文本邮件')
msg['Subject'] = 'Python发送邮件示例'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'

smtp = smtplib.SMTP('smtp.example.com')
smtp.login('username', 'password')
smtp.sendmail('sender@example.com', 'receiver@example.com', msg.as_string())
smtp.quit()

在上面的代码中,我们首先导入了SMTP库和email模块。然后创建了一个纯文本邮件对象msg,设置了消息主题,发件人,收件人等信息。然后打开SMTP连接,通过SMTP服务器发送邮件,并关闭连接。

二、发送带HTML格式的电子邮件

发送HTML格式邮件时,我们需要在MIMEText对象中设置邮件内容为HTML格式,实例如下:

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('<h1>Python发送邮件示例</h1><p>这是一封HTML邮件</p>', 'html', 'utf-8')
msg['Subject'] = 'Python发送邮件示例'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'

smtp = smtplib.SMTP('smtp.example.com')
smtp.login('username', 'password')
smtp.sendmail('sender@example.com', 'receiver@example.com', msg.as_string())
smtp.quit()

在这个代码示例中,我们设置消息主体的内容为HTML格式,并将第二个参数设置为'html'。这样邮件内容就会被解释为HTML代码。

三、发送带附件的电子邮件

有时我们需要通过电子邮件发送附件,比如照片、文档、或其他文件。这时,我们可以使用Python的email.mime.multipart类。此类允许我们将多个MIME对象组合在一起,从而能够同时包含文本和附件。例如:

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

msg = MIMEMultipart()
msg['Subject'] = 'Python发送邮件示例'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'

body = MIMEText('这是一封带附件的邮件')
msg.attach(body)

with open('example.pdf', 'rb') as f:
    attachment = MIMEApplication(f.read(), _subtype='pdf')
    attachment.add_header('Content-Disposition', 'attachment', filename='example.pdf')
    msg.attach(attachment)

smtp = smtplib.SMTP('smtp.example.com')
smtp.login('username', 'password')
smtp.sendmail('sender@example.com', 'receiver@example.com', msg.as_string())
smtp.quit()

在上面的代码中,我们创建了一个MIMEMultipart对象,将文本主体和附件添加到此对象中。我们使用Python的with关键字来打开文件,并将其包含到我们的邮件的附件部分。此外,我们使用add_header()方法来设置附件的文件名和文件类型。

结论

本文介绍了Python编写邮件的公共库的使用方法。Python的smtplib和email模块提供了一种快速、便捷、强大的途径来发送电子邮件。使用Python编写邮件,可以方便的实现自动发送批量邮件、定时发送、发送电子文档等众多功能。