直接使用别人封装好的第三方库:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/5 21:42 # @Author : zhdya # @File : demon.py import yagmail args = { "user": "zhdyaa@163.com", "password": "xxxxx", "host": "smtp.163.com", "port": "465" } yagmail.SMTP(**args) emailList = ['zhdya@zhdya.cn','974644081@qq.com'] email = yagmail.SMTP(**args) email.send(to=emailList, subject="这是主题", contents="这是内容。。", cc="zhdya@qq.com", attachments="Server.py") |
参数:
User 用户民 Password 用户密码,很多情况需要使用授权码 Host smtp的地址 Port 默认使用ssl协议,默认是465端口 To 收件人 Subject 主题 Contents 消息内容 Attachments 附件 Cc 抄送人 |
实例二、
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/6 22:23 # @Author : zhdya # @File : mmail2.py import email.mime.multipart import email.mime.text import smtplib msg = email.mime.multipart.MIMEMultipart() msg['from'] = 'zhdyaa@163.com' msg['to'] = 'zhdya@qq.com' msg['subject'] = 'I like Python' context = '''Now the time is 20180606, I already learning Python from three month, during that time, I found a way which can let me learning fast...''' text = email.mime.text.MIMEText(_text=context, _subtype="html") msg.attach(text) mmail = smtplib.SMTP_SSL() mmail.connect("smtp.163.com", 465) mmail.login("zhdyaa@163.com", "xxxxxxx") mmail.sendmail(from_addr='zhdyaa@163.com', to_addrs='zhdya@qq.com', msg = msg.as_string()) mmail.close() |
通过python发邮件步骤: 前提是:开通了第三方授权,可以使用smtp服务:
创建一个smtp对象
连接smp服务器,默认端口都是25
登录自己邮箱账号,
调用发送消息函数,参数:发件人,收件人,消息内容
关闭连接
mmail = smtplib.SMTP_SSL() mmail.connect("smtp.163.com", 465) mmail.login("zhdyaa@163.com", "xxxxxxx") mmail.sendmail(from_addr='zhdyaa@163.com', to_addrs='zhdya@qq.com', msg = msg.as_string()) mmail.close() |
创建一个消息对象:
msg = email.mime.multipart.MIMEMultipart() msg['from'] = 'zhdyaa@163.com' msg['to'] = 'zhdya@qq.com' msg['subject'] = 'I like Python' |
分别指明邮件的发件人,收件, 只代表显示的问题。
消息内容:
定义一个字符串,来表示你得消息内容:
context = '''Now the time is 20180606, I already learning Python from three month, during that time, I found a way which can let me learning fast...'''
_subtype这个参数就决定了,你是以html解析的形式去发送,还是以text的形式去发送。
最终的效果:
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。