python+smtp邮件

前言

使用smtp发送邮件是一个很常见的互联网应用场景,实现smtp协议发送邮件的方式很多,可以用简单的Telnet命令行,也可以借用springboot等现有框架构建,当然也可以是python的相关类库实现。更多smtp相关的参考《Spring-boot-email邮件》,这里主要记录一下用python实现smtp发送邮件。需要注意的是,发送者邮箱的密码是授权登录密码,否则会返回553未认证错误码,授权码在邮箱设置页面可以找得到。

Smtp邮件样例

demo1

#!/usr/bin/python3
 
import smtplib
import email.mime.multipart
import email.mime.text

msg = email.mime.multipart.MIMEMultipart()
msg['from'] = 'your163email@163.com'
msg['to'] = '1213334346@qq.com'
msg['subject'] = 'sincely from 2019 greeting'
content = 'python email'
'''''
    您好,
            这是来自2019最亲切的问候,by python!
'''
txt = email.mime.text.MIMEText(content)
msg.attach(txt)

smtp = smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com') # 连接smtp服务器
smtp.login('your163email@163.com', 'yourpassword') #邮件账号,登录密码为邮箱授权码
smtp.sendmail('your163email@163.com', '1213334346@qq.com', str(msg))
smtp.quit()

demo2

#!/usr/bin/python3
 
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
 
my_sender='your163email@163.com'    
my_pass = 'yourpassword'            # 邮箱登录授权码
my_user='1213334346@qq.com'      
def mail():
    ret=True
    try:
        msg=MIMEText('dosthing','plain','utf-8')
        msg['From']=formataddr(["dosthing",my_sender])  
        msg['To']=formataddr(["FK",my_user])             
        msg['Subject']="来自2019的最亲切的问候by dosting!"             
 
        server=smtplib.SMTP_SSL("smtp.163.com", 465)  
        server.login(my_sender, my_pass)  
        server.sendmail(my_sender,[my_user,],msg.as_string())  
        server.quit()  
    except Exception:  
        ret=False
    return ret
 
ret=mail()
if ret:
    print("send success")
else:
    print("send fail")

总结

Python总能给你带来一点小惊喜,利用它可以很方便实现一些小应用,代码量也很小,但是很高效,这里整理一下利用python发送smtp邮件,仅记录以作备忘,2018年末于广州。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值