Featured image of post Python Basic 17 smtplib 发送邮件

Python Basic 17 smtplib 发送邮件

本篇文章主要介绍用 Python imaplib 发送邮件

大家好!今天给大家分享如何用Python的smtplib库发送邮件~(◕‿◕✿)

先来个最简单的例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import smtplib

# 创建SMTP连接 (๑•̀ㅂ•́)و✧
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()  # 启用安全传输
server.login('your_email@example.com', 'your_password') 

# 发送邮件 ✉️
server.sendmail(
    'from@example.com', 
    'to@example.com', 
    'Subject: 你好呀~\n\n这是邮件正文内容!'
)

server.quit()
print("邮件发送成功啦!🎉")

参数详解 🔍

SMTP服务器地址

  • 163邮箱:smtp.163.com
  • QQ邮箱:smtp.qq.com
  • Gmail: smtp.gmail.com

端口号

  • 25: 普通SMTP
  • 465: SSL加密
  • 587: TLS加密 (推荐🌟)

进阶用法 🌟

发送HTML邮件

1
2
3
4
5
6
7
8
9
from email.mime.text import MIMEText
from email.header import Header

msg = MIMEText('<h1>我是HTML内容</h1><p>带样式就是不一样!</p>', 'html', 'utf-8')
msg['Subject'] = Header('HTML邮件测试', 'utf-8')
msg['From'] = 'me@example.com'
msg['To'] = 'you@example.com'

server.sendmail(msg['From'], msg['To'], msg.as_string())

添加附件 📎

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

msg = MIMEMultipart()
msg['Subject'] = '带附件的邮件'

# 添加文本
msg.attach(MIMEText('这是正文内容~', 'plain', 'utf-8'))

# 添加附件 (ノ◕ヮ◕)ノ*:・゚✧
with open('report.pdf', 'rb') as f:
    attach = MIMEApplication(f.read(), _subtype='pdf')
    attach.add_header('Content-Disposition', 'attachment', filename='报告.pdf')
    msg.attach(attach)

server.sendmail(msg['From'], msg['To'], msg.as_string())

安全提示 ⚠️

  • 不要把密码写在代码里!(可以用环境变量或配置文件)
  • Gmail需要开启"允许不够安全的应用"
  • 建议使用授权码而不是真实密码

完整示例 👑

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email(to_addr):
    # 创建消息对象
    msg = MIMEMultipart()
    msg['From'] = 'me@example.com'
    msg['To'] = to_addr
    msg['Subject'] = 'Python邮件测试'

    # 邮件正文
    body = """
    <h1>你好呀!</h1>
    <p>这是一封来自Python的测试邮件~</p>
    <p>发送时间:2023-05-20</p>
    """
    msg.attach(MIMEText(body, 'html', 'utf-8'))

    # 发送邮件
    try:
        server = smtplib.SMTP_SSL('smtp.example.com', 465)
        server.login('me@example.com', 'password')
        server.send_message(msg)
        server.quit()
        return True
    except Exception as e:
        print(f"发送失败 😢: {e}")
        return False

# 调用函数
if send_email('friend@example.com'):
    print("发送成功啦!✌️")

记得把示例中的邮箱和密码换成你自己的哦!(。・ω・。)

学会了就用起来吧~有什么问题欢迎留言讨论!✨

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计