用python标准库smtplib来发QQ邮件及Django中发送邮件
1.QQ邮箱设置
点击QQ邮箱账号,进入后,开启smtp服务许可:
点击“生产授权码”,在手机上发送相应的短信,得到授权码。【注意授权码之间没有空格】
2.典型代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 | import smtplib from email.mime.text import MIMEText from email.header import Header msg_from = 'xxxxxxx@qq.com' #发送邮件的邮箱号码 password = 'xxxxxxx' #授权码,不是邮箱登录密码 msg_to = [ 'xxx@qq.com' , 'xxx@qq.com' , 'xxx@qq.com' ] #收件邮箱List message = MIMEText( 'python邮件发送测试...' , 'plain' , 'utf-8' ) message[ 'From' ] = Header( '来自JohnYang' , 'utf-8' ) message[ 'To' ] = Header( '测试' , 'utf-8' ) message[ 'Subject' ] = Header( 'Python SMTP邮件测试' , 'utf-8' ) client = smtplib.SMTP_SSL( 'smtp.qq.com' ,smtplib.SMTP_SSL_PORT) client.login(msg_from,password) client.sendmail(msg_from,msg_to,message.as_string()) #发送 |
3.Django中发送邮件
Django对smptlib进行了包装,使得发送邮件更为简便。
首先在settings.py中添加如下设置:
1 2 3 | EMAIL_HOST = 'smtp.qq.com' EMAIL_PORT = 25 EMAIL_HOST_USER = 'from@example.com' <br><br>EMAIL_HOST_PASSWORD = 'ixxxxxx' <br>EMAIL_USE_TLS = True |
Django中有关邮件的在django.core.mail模块中。
(1)send_mail
1 2 3 4 5 6 7 8 9 | from django.core.mail import send_mail send_mail( 'Subject here' , 'Here is the message.' , 'from@example.com' , [ 'to@example.com' ], fail_silently = False , ) |
(2)send_mass_mail
1 2 3 4 5 | datatuple = ( ( 'Subject' , 'Message.' , 'from@example.com' , [ 'john@example.com' ]), ( 'Subject' , 'Message.' , 'from@example.com' , [ 'jane@example.com' ]), ) send_mass_mail(datatuple) |
(3)EmailMessage类
1 2 3 4 5 6 7 8 9 10 11 12 13 | from django.core.mail import EmailMessage email = EmailMessage( 'Hello' , 'Body goes here' , 'from@example.com' , [ 'to1@example.com' , 'to2@example.com' ], [ 'bcc@example.com' ], reply_to = [ 'another@example.com' ], headers = { 'Message-ID' : 'foo' }, ) message.attach_file( '/images/weather_map.png' ) message.send() |
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix