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

使用Python编写程序通过smtplib发送邮件的步骤

发布时间:2023-12-25 13:22:45

发送邮件是一项常见的任务,Python提供了smtplib模块来实现这个功能。smtplib模块是Python标准库中的一部分,可以用于发送电子邮件。

下面是使用Python通过smtplib发送邮件的步骤:

1. 引入必要的模块

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

2. 设置邮件内容

创建一个MIMEText对象,用于设置邮件的正文内容。可以使用HTML格式或纯文本格式。

msg = MIMEMultipart()
msg["From"] = "sender@example.com"   # 发件人
msg["To"] = "recipient@example.com"  # 收件人
msg["Subject"] = "Hello, World!"     # 邮件主题

body = """
<html>
  <body>
    <h1>Hello, World!</h1>
    <p>This is a test email.</p>
  </body>
</html>
"""

msg.attach(MIMEText(body, "html"))

3. 设置附件(可选)

如果需要发送附件,可以使用MIMEMultipart对象的attach()方法添加附件。

attachment = open("file.txt", "rb")

part = MIMEBase("application", "octet-stream")
part.set_payload((attachment).read())
email.encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment", filename="file.txt")

msg.attach(part)

4. 连接到SMTP服务器

使用smtplib模块的SMTP()类创建一个SMTP对象,并连接到SMTP服务器。

smtp = smtplib.SMTP("smtp.example.com", 587)
smtp.starttls()  # 如果需要加密传输,可以调用starttls()方法
smtp.login("username", "password")  # 登录到SMTP服务器

5. 发送邮件

使用SMTP对象的sendmail()方法发送邮件。

smtp.sendmail("sender@example.com", "recipient@example.com", msg.as_string())  # 发送邮件

6. 关闭SMTP连接

发送完成后,记得调用SMTP对象的quit()方法关闭连接。

smtp.quit()

下面是一个完整的示例,演示如何使用Python通过smtplib发送邮件:

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"] = "Hello, World!"

body = """
<html>
  <body>
    <h1>Hello, World!</h1>
    <p>This is a test email.</p>
  </body>
</html>
"""

msg.attach(MIMEText(body, "html"))

attachment = open("file.txt", "rb")
part = MIMEBase("application", "octet-stream")
part.set_payload((attachment).read())
email.encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment", filename="file.txt")

msg.attach(part)

smtp = smtplib.SMTP("smtp.example.com", 587)
smtp.starttls()
smtp.login("username", "password")
smtp.sendmail("sender@example.com", "recipient@example.com", msg.as_string())
smtp.quit()

注意事项:

- 在使用smtplib发送邮件之前,确保已经安装了Python的smtplib模块和email模块。

- 邮件服务器的地址和端口号需要根据实际情况进行设置。

- 如果邮件服务器需要加密传输,可以调用starttls()方法。

- 在设置邮件内容时,可以使用HTML格式或纯文本格式,根据自己的需求选择。

- 如果需要发送附件,可以使用MIMEText对象的attach()方法添加附件。

总结:

使用Python通过smtplib发送邮件的步骤包括:引入模块、设置邮件内容、设置附件(可选)、连接到SMTP服务器、发送邮件、关闭SMTP连接。注意在实际使用时要根据实际情况进行设置和调整。以上是一个基本的示例,可以根据需要进行扩展和修改。