汇总Python发邮件的15个常用方式(附代码)
Python 提供了多种发送电子邮件的方式,一些常见的方法及其代码汇总:
文章目录
1. 使用 smtplib
模块
smtplib
是 Python 内置的一个模块,用于发送邮件。下面是一个使用 smtplib
发送简单文本邮件的示例:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email_smtp():
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_password"
# 创建邮件对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test Email from smtplib"
# 邮件正文
body = "This is a test email sent from Python using smtplib."
message.attach(MIMEText(body, "plain"))
try:
# 连接到 SMTP 服务器
server = smtplib.SMTP("smtp.example.com", 587)
server.starttls() # 启用安全传输
server.login(sender_email, password)
# 发送邮件
server.sendmail(sender_email, receiver_email, message.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Error: {
e}")
finally:
server.quit()
send_email_smtp()
2. 使用 yagmail
库
yagmail
是一个简化的第三方库,用于发送电子邮件。它封装了 smtplib
,使发送邮件更加容易。
首先,安装 yagmail
库:
pip install yagmail
然后,使用以下代码发送邮件:
import yagmail
def send_email_yagmail():
sender_email = "[email protected]"
password = "your_password"
receiver_email = "[email protected]"
yag = yagmail.SMTP(user=sender_email, password=password)
subject = "Test Email from yagmail"
contents = "This is a test email sent from Python using yagmail."
try:
yag.send(to=receiver_email, subject=subject, contents=contents)
print("Email sent successfully!")
except Exception as e:
print(f"Error: {
e}")
send_email_yagmail()
3. 使用 email
模块和 smtplib
email
模块提供了一个用于构建复杂邮件内容的接口,可以结合 smtplib
发送邮件。
import smtplib
from email.message import EmailMessage
def send_email_email_module():
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_password"
# 创建邮件对象
message = EmailMessage()
message.set_content("This is a test email sent from Python using email module and smtplib.")
message["Subject"] = "Test Email"
message["From"] = sender_email
message["To"] = receiver_email
try:
# 连接到 SMTP 服务器
server = smtplib.SMTP("smtp.example.com", 587)
server.starttls() # 启用安全传输
server.login(sender_email, password)
# 发送邮件
server.send_message(message)
print("Email sent successfully!")
except Exception as e:
print(f"Error: {
e}")
finally:
server.quit()
send_email_email_module()
4. 使用 flask-mail
库(适用于 Flask 应用)
flask-mail
是一个 Flask 扩展,用于在 Flask 应用中发送电子邮件。
首先,安装 flask-mail
:
pip install Flask-Mail
然后,使用以下代码在 Flask 应用中发送邮件:
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 587
app.config
作者:今晚务必早点睡