在日常开发中,发送电子邮件是一个常见的需求。Python 提供了多种方法来发送邮件,下面汇总了15种常用的方式,并附上相应的代码示例。

1. 使用 smtplib 发送简单邮件

smtplib 是 Python 标准库中用于发送邮件的模块。

import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'your_email@example.com'
    msg['To'] = to_email

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('your_email@example.com', 'your_password')
        server.send_message(msg)

send_email('测试主题', '这是一封测试邮件', 'recipient@example.com')

2. 使用带附件的邮件

通过 email 模块,可以发送包含附件的邮件。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment(subject, body, to_email, filename):
    msg = MIMEMultipart()
    msg['From'] = 'your_email@example.com'
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body))

    attachment = MIMEBase('application', 'octet-stream')
    with open(filename, 'rb') as file:
        attachment.set_payload(file.read())
    encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition', f'attachment; filename={filename}')
    msg.attach(attachment)

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('your_email@example.com', 'your_password')
        server.send_message(msg)

send_email_with_attachment('主题', '邮件内容', 'recipient@example.com', 'file.txt')

3. 使用 Gmail 发送邮件

利用 Gmail 的 SMTP 服务器发送邮件。

def send_email_gmail(subject, body, to_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'your_gmail@example.com'
    msg['To'] = to_email

    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login('your_gmail@example.com', 'your_password')
        server.send_message(msg)

send_email_gmail('测试主题', '邮件内容', 'recipient@example.com')

4. 使用 SSL 发送邮件

通过 SSL 连接发送邮件。

def send_email_ssl(subject, body, to_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'your_email@example.com'
    msg['To'] = to_email

    with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
        server.login('your_email@example.com', 'your_password')
        server.send_message(msg)

send_email_ssl('主题', '内容', 'recipient@example.com')

5. 发送 HTML 邮件

通过 MIMEText 发送 HTML 格式的邮件。

def send_html_email(subject, html_body, to_email):
    msg = MIMEText(html_body, 'html')
    msg['Subject'] = subject
    msg['From'] = 'your_email@example.com'
    msg['To'] = to_email

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('your_email@example.com', 'your_password')
        server.send_message(msg)

send_html_email('HTML邮件', '<h1>这是一个HTML邮件</h1>', 'recipient@example.com')

6. 使用第三方库 yagmail 发送邮件

yagmail是一个更简单的邮件发送库,适合发送 Gmail 邮件。

import yagmail

def send_email_yagmail(subject, body, to_email):
    yag = yagmail.SMTP('your_gmail@example.com', 'your_password')
    yag.send(to_email, subject, body)

send_email_yagmail('主题', '内容', 'recipient@example.com')

7. 通过 Outlook 发送邮件

使用 win32com.client 发送 Outlook 邮件。

import win32com.client

def send_email_outlook(subject, body, to_email):
    outlook = win32com.client.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.Subject = subject
    mail.Body = body
    mail.To = to_email
    mail.Send()

send_email_outlook('主题', '内容', 'recipient@example.com')

8. 使用 Flask 发送邮件

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['MAIL_USERNAME'] = 'your_email@example.com'
app.config['MAIL_PASSWORD'] = 'your_password'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail = Mail(app)

def send_email_flask(subject, body, to_email):
    msg = Message(subject, sender='your_email@example.com', recipients=[to_email])
    msg.body = body
    mail.send(msg)

send_email_flask('主题', '内容', 'recipient@example.com')

9. 发送带图片的邮件

可以通过 MIMEImage 发送带有图片的邮件。

from email.mime.image import MIMEImage

def send_email_with_image(subject, body, to_email, image_path):
    msg = MIMEMultipart()
    msg['From'] = 'your_email@example.com'
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body))

    with open(image_path, 'rb') as img:
        image = MIMEImage(img.read())
        msg.attach(image)

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('your_email@example.com', 'your_password')
        server.send_message(msg)

send_email_with_image('主题', '内容', 'recipient@example.com', 'image.png')

10. 发送批量邮件

可以利用循环,批量发送邮件。

def send_bulk_emails(subject, body, email_list):
    for email in email_list:
        send_email(subject, body, email)

email_list = ['recipient1@example.com', 'recipient2@example.com']
send_bulk_emails('主题', '内容', email_list)

11. 定时发送邮件

结合 schedule 库,可以实现定时发送邮件。

import schedule
import time

def job():
    send_email('定时邮件', '这是定时发送的邮件', 'recipient@example.com')

schedule.every().day.at("10:30").do(job)

while True:
    schedule.run_pending()
    time.sleep(60)

12. 发送带有 CC 和 BCC 的邮件

使用 CCBCC 发送邮件。

def send_email_cc_bcc(subject, body, to_email, cc_email, bcc_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'your_email@example.com'
    msg['To'] = to_email
    msg['Cc'] = cc_email

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login('your_email@example.com', 'your_password')
        server.send_message(msg, to_addrs=[to_email, cc_email, bcc_email])

send_email_cc_bcc('主题', '内容', 'recipient@example.com', 'cc@example.com', 'bcc@example.com')

13. 使用 SMTP 配置环境变量

为了安全起见,可以将 SMTP 配置信息存储为环境变量。

import os

os.environ['EMAIL_USER'] = 'your_email@example.com'
os.environ['EMAIL_PASS'] = 'your_password'

def send_email_env(subject, body, to_email):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = os.getenv('EMAIL_USER')
    msg['To'] = to_email

    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login(os.getenv('EMAIL_USER'), os.getenv('EMAIL_PASS'))
        server.send_message(msg)

send_email_env('主题', '内容', 'recipient@example.com')

14. 使用模板引擎生成邮件内容

可以使用 Jinja2 生成邮件的 HTML 内容。

from jinja2 import Template

def render_email_template(subject, recipient_name):
    template = Template("""
    <html>
    <body>
        <h1>Hello {{ name }}</h1>
        <p>欢迎使用我们的网站!</p>
    </body>
    </html>
    """)
    return template.render(name=recipient_name)

html_content = render_email_template('主题', '用户')
send_html_email('主题', html_content, 'recipient@example.com')

15. 处理发送邮件的异常

在发送邮件时,使用 try-except 捕获异常。

def safe_send_email(subject, body, to_email):
    try:
        send_email(subject, body, to_email)
        print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {e}")

safe_send_email('主题', '内容', 'recipient@example.com')

总结

以上是 Python 发送邮件的15种常用方式,涵盖了从简单的文本邮件到带附件、HTML 及批量发送等各种场景。通过这些示例,开发者可以根据具体需求灵活应用,提升邮件处理的效率。

点赞(0) 打赏

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部