前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Python 3发邮件

使用Python 3发邮件

作者头像
老七Linux
发布2018-06-07 10:38:05
8910
发布2018-06-07 10:38:05
举报

示例一:(使用yagmail模块)

直接使用别人封装好的第三方库:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/5 21:42
# @Author  : zhdya
# @File    : demon.py

import yagmail

args = {

    "user": "[email protected]",
    "password": "xxxxx",
    "host": "smtp.163.com",
    "port": "465"
}

yagmail.SMTP(**args)

emailList =  ['[email protected]','[email protected]']

email = yagmail.SMTP(**args)
email.send(to=emailList, subject="这是主题", contents="这是内容。。", cc="[email protected]", 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'] = '[email protected]'
msg['to'] = '[email protected]'
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("[email protected]", "xxxxxxx")
mmail.sendmail(from_addr='[email protected]', to_addrs='[email protected]', msg = msg.as_string())
mmail.close()

通过python发邮件步骤: 前提是:开通了第三方授权,可以使用smtp服务:

  1. 创建一个smtp对象
  2. 连接smp服务器,默认端口都是25
  3. 登录自己邮箱账号,
  4. 调用发送消息函数,参数:发件人,收件人,消息内容
  5. 关闭连接
mmail = smtplib.SMTP_SSL()
mmail.connect("smtp.163.com", 465)
mmail.login("[email protected]", "xxxxxxx")
mmail.sendmail(from_addr='[email protected]', to_addrs='[email protected]', msg = msg.as_string())
mmail.close()
创建一个消息对象:
msg = email.mime.multipart.MIMEMultipart()
msg['from'] = '[email protected]'
msg['to'] = '[email protected]'
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的形式去发送。

最终的效果:

mark
mark
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018/06/06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例一:(使用yagmail模块)
  • 实例二、
    • 创建一个消息对象:
      • 消息内容:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档