python实现发送邮件超简单
Posted _刘文凯_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现发送邮件超简单相关的知识,希望对你有一定的参考价值。
python实现发送邮件【超简单】python如何发送邮件(使用QQ邮箱)
1、只发送信息
def send_msg(msg):
my_sender = '371500112@qq.com' # 发件人邮箱账号
my_pass = 'krbbydaossjobjfa' # 发件人邮箱授权码!! 这里不是密码!!
to_user = '173795448@qq.com' # 收件人邮箱账号,我这边发送给自己
msg = msg # 要发的信息
# 登陆邮箱
sent = smtplib.SMTP()
sent.connect('smtp.qq.com', 25)
mail_name = my_sender # 发送人邮箱地址
mail_password = my_pass # 注意:这里不是密码,而应该填写授权码!!
sent.login(mail_name, mail_password) # 登陆
# 编辑邮件内容
to_user_list = [to_user] # 收件人邮箱地址
content = MIMEText(msg) # 正文内容
content['From'] = 'xs' # 发件人
content['Subject'] = 'XS-ID' # 邮件标题
content['To'] = ','.join(to_user_list) # 收件人,用逗号连接多个邮件,实现群发
# 发送邮件
try:
sent.sendmail(mail_name, to_user_list, content.as_string()) # 3个参数 发送人,收件人,邮件内容
print('Success')
sent.close()
except smtplib.SMTPException:
print("Error:Fail")
if __name__ == '__main__':
msg = '你是大好人!'
send_msg(msg):
2、发送带有附件的邮箱
def send_att(msg):
my_sender = '371500112@qq.com' # 发件人邮箱账号
my_pass = 'krbbydaossjobjfa' # 发件人邮箱授权码!! 这里不是密码!!
to_user = '173795448@qq.com' # 收件人邮箱账号,我这边发送给自己
msg = msg
# 登陆邮箱
sent = smtplib.SMTP()
sent.connect('smtp.qq.com', 25)
mail_name = my_sender # 发送人邮箱地址
mail_password = my_pass # 注意:这里不是密码,而应该填写授权码!!
sent.login(mail_name, mail_password) # 登陆
# 编辑邮件内容
to_user_list = [to_user] # 收件人邮箱地址
message = MIMEMultipart()
message['From'] = Header('XS', 'utf-8')
message['Subject'] = Header('xxss', 'utf-8')
message['To'] = Header("User", 'utf-8')
message.attach(MIMEText(msg, 'plain', 'utf-8'))
# 添加附件1
try:
send_file = './test.csv'
att1 = MIMEText(open(send_file).read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="test.csv"' # 这里的filename是邮件中显示什么名字
message.attach(att1)
except Exception:
print('发送邮件时,文件不存在。。')
try:
sent.sendmail(mail_name, to_user_list, message.as_string()) # 3个参数 发送人,收件人,邮件内容
print('Success')
sent.close()
except smtplib.SMTPException:
print("Error:Fail")
if __name__ == '__main__':
msg = '你是大好人!'
send_att(msg):
3、QQ邮箱如何开启授权码
参考:https://blog.csdn.net/weixin_44915703/article/details/104417030
以上是关于python实现发送邮件超简单的主要内容,如果未能解决你的问题,请参考以下文章