需要用163邮箱向办公邮箱发送数据,搜索大量代码发现两个亲测可用的代码,转载过来。
其中添加附件的我做了修改,不然发送不成功,不带附件的代码如下:
import smtplib
from email.mime.text import MIMEText
mailserver = "smtp.163.com" # 邮箱服务器地址
username_send = 'ahtgyy@163.com' # 邮箱用户名
password = 'WMTXRMGGIEURQNTL' # 邮箱密码:需要使用授权码--填写自己独有的
username_recv = ['395827040@qq.com'] # 收件人,多个收件人用逗号隔开
mail = MIMEText('这是自动发送的信托净值\n不要回复')
mail['Subject'] = '上海信托现金丰利净值'
mail['From'] = username_send # 发件人
mail['To'] = ",".join(username_recv) # 收件人;[]里的三个是固定写法,别问为什么,我只是代码的搬运工
#join 函数的应用,前面按照常理来说是";"分号,但是我试过,分号没有用,只能用","才能顺利发送。这个可能跟163邮箱自身有关
smtp = smtplib.SMTP(mailserver, port=25) # 连接邮箱服务器,smtp的端口号是25
# smtp=smtplib.SMTP_SSL('smtp.qq.com',port=465) #QQ邮箱的服务器和端口号
smtp.login(username_send, password) # 登录邮箱
smtp.sendmail(username_send, username_recv, mail.as_string()) # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.quit() # 发送完毕后退出smtp
print('success')
博文原地址:
原地址
带附件的代码:
# -*- coding: utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
mail_host ='smtp.163.com' #mail_host = 'smtp.qq.com'
port=25 #QQ邮箱是465
send_by = 'aht@163.com'
password = 'WMTXRMGGI'
username_recv = ['3958@qq.com']# 收件人,多个收件人用逗号隔开
msg = MIMEMultipart() # 创建一个带附件的实例
msg["Subject"] = "托管自动发邮件测试"
msg["From"] = send_by
# ---文字部分---
part = MIMEText("这是自动发送的信托净值,请查收,谢谢!")
msg.attach(part)
# ---附件部分---
part = MIMEApplication(open('丰利净值.xlsx', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="丰利净值.xlsx")
msg.attach(part)
# 要注意位置参数和关键字参数啊啊
smtp = smtplib.SMTP(mail_host, port, 'utf-8')#原博主使用的是smpt = smtplib.SMTP_SSL(mail_host, port, 'utf-8'),163邮箱会报错
smtp.login(send_by, password)
smtp.sendmail(send_by, username_recv, msg.as_string())
smtp.quit()
print("发送成功")
其中最后一段我标记了原博主写的和我写的不一样我用原博主的无法发送,改成我这样的成功了,打开可以试试
原博文地址:
原地址