Python中如何使用email.message模块发送电子邮件
发布时间:2023-12-27 17:04:11
在Python中,我们可以使用email.message模块来创建和发送电子邮件。这个模块提供了一种简单和灵活的方式来处理电子邮件消息,包括设置发送者、接收者、主题、正文以及附件等。
首先,我们需要导入相关的模块:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage
接下来,我们可以创建一个邮件消息对象,并设置发送者、接收者、主题等信息:
msg = MIMEMultipart() msg['From'] = 'sender@example.com' msg['To'] = 'recipient@example.com' msg['Subject'] = 'Hello from Python!'
然后,我们可以设置邮件的正文内容。如果只是纯文本内容,我们可以使用MIMEText类,如下所示:
body = 'This is the body of the email' msg.attach(MIMEText(body, 'plain'))
如果我们还想在邮件中添加附件,可以使用MIMEImage类或者MIMEText类,并将它们附加到邮件消息对象上:
with open('image.jpg', 'rb') as image_file:
image_content = image_file.read()
image = MIMEImage(image_content, 'jpg')
image.add_header('Content-Disposition', 'attachment', filename='image.jpg')
msg.attach(image)
with open('document.pdf', 'rb') as document_file:
document_content = document_file.read()
document = MIMEText(document_content, 'pdf')
document.add_header('Content-Disposition', 'attachment', filename='document.pdf')
msg.attach(document)
最后,我们需要将电子邮件发送出去。首先,我们需要设置SMTP服务器的地址和端口号,以及验证信息。然后,我们可以使用smtplib模块的sendmail函数来发送邮件:
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
这样,我们就成功地使用email.message模块发送了一封带有附件的电子邮件。
完整例子代码如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Hello from Python!'
body = 'This is the body of the email'
msg.attach(MIMEText(body, 'plain'))
with open('image.jpg', 'rb') as image_file:
image_content = image_file.read()
image = MIMEImage(image_content, 'jpg')
image.add_header('Content-Disposition', 'attachment', filename='image.jpg')
msg.attach(image)
with open('document.pdf', 'rb') as document_file:
document_content = document_file.read()
document = MIMEText(document_content, 'pdf')
document.add_header('Content-Disposition', 'attachment', filename='document.pdf')
msg.attach(document)
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
这个例子演示了如何使用email.message模块通过SMTP服务器发送带有附件的电子邮件。你可以根据自己的需求修改邮件的内容和设置。
