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

通过Python中的Message()发送电子邮件

发布时间:2023-12-24 01:40:55

在Python中,可以使用smtplib模块来发送电子邮件。smtplib是Python的标准库,无需安装即可使用。下面是一个使用Message()函数发送电子邮件的例子。

首先,需要导入所需的模块:

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

然后,创建一个Message对象并设置邮件的发送者,接收者,主题和内容:

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'This is the subject of the email'
body = 'This is the content of the email.'
msg.attach(MIMEText(body, 'plain'))

接下来,如果需要附加文件,则可以使用add_attachment()方法添加文件附件:

filename = 'attachment.txt'
attachment = open(filename, 'rb')
part = MIMEBase('application/octet-stream', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)

然后,创建一个smtplib.SMTP对象并连接到邮件服务器:

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('sender@example.com', 'password')

接下来,发送电子邮件:

text = msg.as_string()
server.sendmail('sender@example.com', 'recipient@example.com', text)
server.quit()

完整的例子如下:

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

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'This is the subject of the email'
body = 'This is the content of the email.'
msg.attach(MIMEText(body, 'plain'))

filename = 'attachment.txt'
attachment = open(filename, 'rb')
part = MIMEBase('application/octet-stream', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('sender@example.com', 'password')

text = msg.as_string()
server.sendmail('sender@example.com', 'recipient@example.com', text)
server.quit()

请注意,上述代码中的"sender@example.com"需要替换为发送者的电子邮件地址,"recipient@example.com"需要替换为收件人的电子邮件地址以及"password"需要替换为发送者电子邮件的密码。

通过以上代码块你可以实现使用Message()发送电子邮件。