python 邮件模块_python学习笔记8-邮件模块

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

username='xxx@xx.com'

email_host = 'smtp.163.com'

passwd='123456'

recv=['511402865@qq.com',]

title='邮件标题'

content='发送邮件测试'

msg = MIMEMultipart()

file='a.txt'

att = MIMEText(open(file,encoding='utf-8').read())

att["Content-Type"] = 'application/octet-stream'

att["Content-Disposition"] = 'attachment; filename="%s"'%file

msg.attach(att)

msg.attach(MIMEText(content))#邮件正文的内容

msg['Subject'] = title # 邮件主题

msg['From'] = username # 发送者账号

msg['To'] = recv # 接收者账号列表

#smtp = smtplib.SMTP_SSL(eail_host,port=456)#qq邮箱

smtp = smtplib.SMTP_SSL(eail_host,port=25)#其他邮箱

smtp.login(username,passwd)

smtp.sendmail(username,recv,msg.as_string())

smtp.quit()

当然,我们可以封装成一个函数,使用的时候,直接调用函数,传入邮箱账号密码,收件人,发件人,标题和内容即可。

import smtplib

from email.mime.text import MIMEText

def send_mail(username,passwd,recv,title,content,mail_host='smtp.163.com',port=25):

'''

发送邮件函数,默认使用163smtp

:param username: 邮箱账号 xx@163.com

:param passwd: 邮箱密码

:param recv: 邮箱接收人地址,多个账号以逗号隔开

:param title: 邮件标题

:param content: 邮件内容

:param mail_host: 邮箱服务器

:param port: 端口号

:return:

'''

msg = MIMEText(content) # 邮件内容

msg['Subject'] = title # 邮件主题

msg['From'] = username # 发送者账号

msg['To'] = recv # 接收者账号列表

smtp = smtplib.SMTP(mail_host,port=port) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25

smtp.login(username, passwd) # 发送者的邮箱账号,密码

smtp.sendmail(username, recv, msg.as_string())

# 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串

smtp.quit() # 发送完毕后退出smtp

print ('email send success.')

email_user = 'xxxx@163.com' # 发送者账号

email_pwd = 'xxxxx' # 发送者密码

maillist ='511402865@qq.com'

title = '测试邮件标题'

content = '这里是邮件内容'

send_mail(email_user,email_pwd,maillist,title,content)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值