利用Python和smtplib库实现高效邮件发送

使用Python的smtplib库发送邮件是一个常见的任务。下面是一个基本的示例,演示如何使用smtplibemail模块发送电子邮件。

图片[1]_利用Python和smtplib库实现高效邮件发送_知途无界

步骤

  1. 导入必要的库
    • smtplib:用于与SMTP服务器进行通信。
    • email.mime.multipart 和 email.mime.text:用于构建邮件内容。
  2. 创建邮件内容
    • 使用email.mime.multipart.MIMEMultipart创建一个多部分邮件对象。
    • 使用email.mime.text.MIMEText添加邮件正文。
  3. 配置SMTP服务器
    • 使用smtplib.SMTP连接到SMTP服务器。
    • 使用login方法登录到SMTP服务器(如果需要)。
  4. 发送邮件
    • 使用sendmail方法发送邮件。

示例代码

以下是一个完整的示例代码,用于发送带有纯文本和HTML内容的电子邮件:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 发件人信息
sender_email = "your_email@example.com"
sender_password = "your_password" # 注意:不要在代码中硬编码密码,使用环境变量或更安全的方式
# 收件人信息
receiver_email = "receiver_email@example.com"
# 创建MIMEMultipart对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test Email Subject"
# 邮件正文(纯文本)
body_text = "This is a test email sent from Python using smtplib."
text_part = MIMEText(body_text, "plain")
# 邮件正文(HTML)
body_html = """
<html>
<head></head>
<body>
<h1>This is a test email</h1>
<p>Sent from Python using <a href="https://docs.python.org/3/library/smtplib.html">smtplib</a>.</p>
</body>
</html>
"""
html_part = MIMEText(body_html, "html")
# 将文本和HTML部分附加到邮件中
message.attach(text_part)
message.attach(html_part)
# 连接到SMTP服务器(例如Gmail)
try:
server = smtplib.SMTP("smtp.gmail.com", 587) # 对于Gmail,使用端口587(TLS)或465(SSL)
server.starttls() # 启用TLS加密
server.login(sender_email, sender_password) # 登录到SMTP服务器
server.sendmail(sender_email, receiver_email, message.as_string()) # 发送邮件
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
server.quit() # 关闭连接
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 发件人信息
sender_email = "your_email@example.com"
sender_password = "your_password"  # 注意:不要在代码中硬编码密码,使用环境变量或更安全的方式

# 收件人信息
receiver_email = "receiver_email@example.com"

# 创建MIMEMultipart对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test Email Subject"

# 邮件正文(纯文本)
body_text = "This is a test email sent from Python using smtplib."
text_part = MIMEText(body_text, "plain")

# 邮件正文(HTML)
body_html = """
<html>
<head></head>
<body>
<h1>This is a test email</h1>
<p>Sent from Python using <a href="https://docs.python.org/3/library/smtplib.html">smtplib</a>.</p>
</body>
</html>
"""
html_part = MIMEText(body_html, "html")

# 将文本和HTML部分附加到邮件中
message.attach(text_part)
message.attach(html_part)

# 连接到SMTP服务器(例如Gmail)
try:
    server = smtplib.SMTP("smtp.gmail.com", 587)  # 对于Gmail,使用端口587(TLS)或465(SSL)
    server.starttls()  # 启用TLS加密
    server.login(sender_email, sender_password)  # 登录到SMTP服务器
    server.sendmail(sender_email, receiver_email, message.as_string())  # 发送邮件
    print("Email sent successfully!")
except Exception as e:
    print(f"Failed to send email: {e}")
finally:
    server.quit()  # 关闭连接
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # 发件人信息 sender_email = "your_email@example.com" sender_password = "your_password" # 注意:不要在代码中硬编码密码,使用环境变量或更安全的方式 # 收件人信息 receiver_email = "receiver_email@example.com" # 创建MIMEMultipart对象 message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = "Test Email Subject" # 邮件正文(纯文本) body_text = "This is a test email sent from Python using smtplib." text_part = MIMEText(body_text, "plain") # 邮件正文(HTML) body_html = """ <html> <head></head> <body> <h1>This is a test email</h1> <p>Sent from Python using <a href="https://docs.python.org/3/library/smtplib.html">smtplib</a>.</p> </body> </html> """ html_part = MIMEText(body_html, "html") # 将文本和HTML部分附加到邮件中 message.attach(text_part) message.attach(html_part) # 连接到SMTP服务器(例如Gmail) try: server = smtplib.SMTP("smtp.gmail.com", 587) # 对于Gmail,使用端口587(TLS)或465(SSL) server.starttls() # 启用TLS加密 server.login(sender_email, sender_password) # 登录到SMTP服务器 server.sendmail(sender_email, receiver_email, message.as_string()) # 发送邮件 print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {e}") finally: server.quit() # 关闭连接

注意事项

  1. 安全性
    • 不要在代码中硬编码密码。使用环境变量或加密存储。
    • 使用应用专用密码(如果SMTP服务器支持)而不是主密码。
  2. SMTP服务器配置
    • 对于不同的邮件服务提供商(如Gmail、Outlook等),SMTP服务器地址和端口可能不同。
    • 某些邮件服务提供商可能需要额外的配置(如允许不太安全的应用访问)。
  3. 异常处理
    • 添加适当的异常处理,以便在发送邮件失败时能够捕获并处理错误。
  4. 调试
    • 在开发过程中,可以使用print语句或日志记录来调试邮件发送过程。

通过以上步骤和示例代码,你应该能够使用Python的smtplib库成功发送电子邮件。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞88 分享
Not all of us can offord to be romantic.
并不是我们所有的人都会拥有浪漫
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容