iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python3 使用smtplib和em
  • 951
分享到

Python3 使用smtplib和em

smtplibem 2023-01-31 08:01:39 951人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

SMTP (Simple Mail Transfer Protocol)  邮件传送代理 (Mail Transfer Agent,MTA) 程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件

SMTP (Simple Mail Transfer Protocol)
  邮件传送代理 (Mail Transfer Agent,MTA) 程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件。大多数的邮件发送服务器 (OutGoing Mail Server) 都是使用SMTP协议。SMTP协议的默认tcp端口号是25。

  SMTP协议的一个重要特点是它能够接力传送邮件。它工作在两种情况下:一是电子邮件从客户机传输到服务器;二是从某一个服务器传输到另一个服务器。

 

POP3 (Post Office Protocol) & IMAP (Internet Message Access Protocol)
  POP协议和IMAP协议是用于邮件接收的最常见的两种协议。几乎所有的邮件客户端和服务器都支持这两种协议。
  POP3协议为用户提供了一种简单、标准的方式来访问邮箱和获取电邮。使用POP3协议的电邮客户端通常的工作过程是:连接服务器、获取所有信息并保存在用户主机、从服务器删除这些消息然后断开连接。POP3协议的默认TCP端口号是110。

  IMAP协议也提供了方便的邮件下载服务,让用户能进行离线阅读。使用IMAP协议的电邮客户端通常把信息保留在服务器上直到用户显式删除。这种特性使得多个客户端可以同时管理一个邮箱。IMAP协议提供了摘要浏览功能,可以让用户在阅读完所有的邮件到达时间、主题、发件人、大小等信息后再决定是否下载。IMAP协议的默认TCP端口号是143。

 

邮件格式 (RFC 2822)
  每封邮件都有两个部分:邮件头和邮件体,两者使用一个空行分隔。
  邮件头每个字段 (Field) 包括两部分:字段名和字段值,两者使用冒号分隔。有两个字段需要注意:From和Sender字段。From字段指明的是邮件的作者,Sender字段指明的是邮件的发送者。如果From字段包含多于一个的作者,必须指定Sender字段;如果From字段只有一个作者并且作者和发送者相同,那么不应该再使用Sender字段,否则From字段和Sender字段应该同时使用。
  邮件体包含邮件的内容,它的类型由邮件头的Content-Type字段指明。RFC 2822定义的邮件格式中,邮件体只是单纯的ASCII编码的字符序列。
MIME (Multipurpose Internet Mail Extensions) (RFC 1341)

  MIME扩展邮件的格式,用以支持非ASCII编码的文本、非文本附件以及包含多个部分 (multi-part) 的邮件体等。

 

Python email模块

1. class email.message.Message
__getitem__,__setitem__实现obj[key]形式的访问。
Msg.attach(playload): 向当前Msg添加playload。
Msg.set_playload(playload): 把整个Msg对象的邮件体设成playload。

Msg.add_header(_name, _value, **_params): 添加邮件头字段。

2. class email.mime.base.MIMEBase(_maintype, _subtype, **_params)

  所有MIME类的基类,是email.message.Message类的子类。

3. class email.mime.multipart.MIMEMultipart()

  在3.0版本的email模块 (python 2.3-Python 2.5) 中,这个类位于email.MIMEMultipart.MIMEMultipart。

  这个类是MIMEBase的直接子类,用来生成包含多个部分的邮件体的MIME对象。

4. class email.mime.text.MIMEText(_text)

  使用字符串_text来生成MIME对象的主体文本。


1、发邮件代码范例:

# -*- coding:utf-8 -*-

import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE,fORMatdate
from email import encoders

#server['name'], server['user'], server['passwd']
def send_mail(server, fro, to, subject="", text="", files=[]):
    assert type(server) == dict
    assert type(to) == list
    assert type(files) == list

    msg = MIMEMultipart()
    msg['From'] = fro                # 邮件的发件人
    msg['Subject'] = subject         # 邮件的主题
    msg['To'] = COMMASPACE.join(to)  # COMMASPACE==', ' 收件人可以是多个,to是一个列表
    msg['Date'] = formatdate(localtime=True) # 发送时间,当不设定时,用outlook收邮件会不显示日期,QQ网页邮箱会显示日期
    # MIMIMEText有三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码,二和三可以省略不写
    msg.attach(MIMEText(text,'plain','utf-8'))

    for file in files:          # 添加附件可以是多个,files是一个列表,可以为空
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data
        with open(file,'rb') as f:
            part.set_payload(f.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'p_w_upload; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    smtp = smtplib.SMTP()
    # smtp = smtplib.SMTP_SSL()  # 使用SSL的方式去登录(例如QQ邮箱,端口是465)
    smtp.connect(server['name']) # connect有两个参数,第一个为邮件服务器,第二个为端口,默认是25
    smtp.login(server['user'], server['passwd']) # 用户名,密码
    smtp.sendmail(fro, to, msg.as_string()) # 发件人,收件人,发送信息
    smtp.close()  # 关闭连接

if __name__ == '__main__':
    server = {'name':'xxx.163.com',
              'user':'babyshen',
              'passwd':'xxoo'}
    fro = 'xxoo'
    to = ['xxx']
    subject = 'test002'
    text = '''test000002'''
    send_mail(server,fro,to,subject,text)

smtp = smtplib.SMTP()

smtp.connect(server['name'])

这两句也可以写成

smtp = smtplib.SMTP(server['name'])


msg[From] 这里既然不是真正的发件人,那是不是可以用来伪造邮件和发送垃圾邮件??

答案是对的,可以用来伪造邮件和发送垃圾邮件,只需要修改这个msg[From]即可


SMTP对象使用sendmail方法发送邮件,语法如下:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

参数说明:

  from_addr: 邮件发送者地址。

  to_addrs: 字符串列表,邮件发送地址。

  msg: 发送消息

这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。


2、文件形式的邮件:

#!/usr/bin/env python3    
#coding: utf-8    
  
import smtplib    
from email.mime.text import MIMEText    
from email.header import Header    
    
sender = '***'    
receiver = '***'    
subject = 'python email test'    
smtpserver = 'smtp.163.com'    
username = '***'    
passWord = '***'    
    
msg = MIMEText('你好','text','utf-8') #中文需参数‘utf-8’,单字节字符不需要    
msg['Subject'] = Header(subject, 'utf-8')    
    
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')    
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msg.as_string())    
smtp.quit()

3、html形式的邮件:

#!/usr/bin/env python3    
#coding: utf-8    
  
import smtplib    
from email.mime.text import MIMEText    
    
sender = '***'    
receiver = '***'    
subject = 'python email test'    
smtpserver = 'smtp.163.com'    
username = '***'    
password = '***'    
    
msg = MIMEText('<html><h1><a href="Http://www.xxoo.com">这是一个链接</a</h1></html>','html','utf-8')    
    
msg['Subject'] = subject    
    
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')    
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msg.as_string())    
smtp.quit()

4、带图片的HTML形式的邮件

#!/usr/bin/env python3    
#coding: utf-8    
  
import smtplib    
from email.mime.multipart import MIMEMultipart    
from email.mime.text import MIMEText    
from email.mime.p_w_picpath import MIMEImage    
    
sender = '***'    
receiver = '***'    
subject = 'python email test'    
smtpserver = 'smtp.163.com'    
username = '***'    
password = '***'    
    
msgRoot = MIMEMultipart('related')    
msgRoot['Subject'] = 'test message'    
    
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an p_w_picpath.<br><img src="cid:p_w_picpath1"><br>good!','html','utf-8')    
msgRoot.attach(msgText)    
    
fp = open('h:\\python\\1.jpg', 'rb')    
msgImage = MIMEImage(fp.read())    
fp.close()    
    
msgImage.add_header('Content-ID', '<p_w_picpath1>')    
msgRoot.attach(msgImage)    
    
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')    
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msgRoot.as_string())    
smtp.quit()

5、带附件的邮件

#!/usr/bin/env python3    
#coding: utf-8    
  
import smtplib    
from email.mime.multipart import MIMEMultipart    
from email.mime.text import MIMEText    
from email.mime.p_w_picpath import MIMEImage    
    
sender = '***'    
receiver = '***'    
subject = 'python email test'    
smtpserver = 'smtp.163.com'    
username = '***'    
password = '***'    
    
msgRoot = MIMEMultipart('related')    
msgRoot['Subject'] = 'test message'    
    
#构造附件    
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')    
att["Content-Type"] = 'application/octet-stream'    
att["Content-Disposition"] = 'p_w_upload; filename="1.jpg"'    
msgRoot.attach(att)    
            
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')    
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msgRoot.as_string())    
smtp.quit()

6、群邮件

#!/usr/bin/env python3    
#coding: utf-8   
   
import smtplib    
from email.mime.text import MIMEText    
    
sender = '***'    
receiver = ['***','****',……]    
subject = 'python email test'    
smtpserver = 'smtp.163.com'    
username = '***'    
password = '***'    
    
msg = MIMEText('你好','text','utf-8')    
    
msg['Subject'] = subject    
    
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')    
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msg.as_string())    
smtp.quit()

7、各种元素都包含的邮件

#!/usr/bin/env python3    
#coding: utf-8    
  
import smtplib    
from email.mime.multipart import MIMEMultipart    
from email.mime.text import MIMEText    
from email.mime.p_w_picpath import MIMEImage    
    
sender = '***'    
receiver = '***'    
subject = 'python email test'    
smtpserver = 'smtp.163.com'    
username = '***'    
password = '***'    
    
# Create message container - the correct MIME type is multipart/alternative.    
msg = MIMEMultipart('alternative')    
msg['Subject'] = "Link"    
    
# Create the body of the message (a plain-text and an HTML version).    
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"    
html = """\  
<html>  
  <head></head>  
  <body>  
    <p>Hi!<br>  
       How are you?<br>  
       Here is the <a href="http://www.python.org">link</a> you wanted.  
    </p>  
  </body>  
</html>  
"""    
    
# Record the MIME types of both parts - text/plain and text/html.    
part1 = MIMEText(text, 'plain')    
part2 = MIMEText(html, 'html')    
    
# Attach parts into message container.    
# According to RFC 2046, the last part of a multipart message, in this case    
# the HTML message, is best and preferred.    
msg.attach(part1)    
msg.attach(part2)    
#构造附件    
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')    
att["Content-Type"] = 'application/octet-stream'    
att["Content-Disposition"] = 'p_w_upload; filename="1.jpg"'    
msg.attach(att)    
       
smtp = smtplib.SMTP()    
smtp.connect('smtp.163.com')    
smtp.login(username, password)    
smtp.sendmail(sender, receiver, msg.as_string())    
smtp.quit()


--结束END--

本文标题: Python3 使用smtplib和em

本文链接: https://www.lsjlt.com/news/192615.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python3 使用smtplib和em
    SMTP (Simple Mail Transfer Protocol)  邮件传送代理 (Mail Transfer Agent,MTA) 程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件...
    99+
    2023-01-31
    smtplib em
  • python3使用smtplib发送邮件,带xlsx附件
    最近在做一个统计报表,需要发送邮件,并带附件的。在之前的文章中https://www.cnblogs.com/xiao987334176/p/10022026.html已经实现了发送邮件,但是没有实现发送附件功能。 send_ma...
    99+
    2023-01-31
    发送邮件 附件 smtplib
  • [Python]使用smtplib类库发
      可以先去Mailgun注册一个免费的programmable mail servers,免费的有每天200封邮件的限制。 Mailgun is a set of powerful APIs that allow you ...
    99+
    2023-01-31
    类库 Python smtplib
  • python3利用smtplib通过qq邮箱发送邮件方法示例
    前言 本文主要给大家介绍了关于python3 smtplib通过qq邮箱发送邮件的相关内容, smtplib模块是smtp简单邮件传输协议客户端的实现,为了通用性,有时候发送邮件的时候要带附件或图片,用em...
    99+
    2022-06-04
    示例 发送邮件 邮箱
  • python中如何使用smtplib模块
    python中如何使用smtplib模块,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。说明创建SMTP的操作对象,连接smtp目标服务器,可以是163、QQ等。根据您的账户...
    99+
    2023-06-20
  • web中rem和em怎么用
    这篇文章给大家分享的是有关web中rem和em怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。1、rem转化为向素值的方法rem单位转化为像素大小取决于根元素的字体大小,即H...
    99+
    2022-10-19
  • px、em和rem怎么应用
    这篇文章主要讲解了“px、em和rem怎么应用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“px、em和rem怎么应用”吧!1px有多大?我们先了解几个概念:关键概念设备像素:设备屏幕实际拥...
    99+
    2023-06-03
  • Python使用smtplib 实现单发和群发邮件验证码
    目录smtplib库SMTP邮件服务器实战1.126邮箱一般默认关闭SMTP服务,我们得先去开启它2.Python代码前言: Python smtplib 教程:展示了如何使用 sm...
    99+
    2022-11-11
  • python使用电子邮件模块smtplib的方法
    Smptp类定义:smtplib.SMTP(host[,port[,local_hostname[,,timeout]]]),作为SMTP的构造函数,功能是与smtp服务器建立连接,在连接成功后,就可以向服...
    99+
    2022-06-04
    模块 电子邮件 方法
  • html css使用em有什么作用
    这篇“html css使用em有什么作用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“ht...
    99+
    2022-10-19
  • oracle不能使用EM怎么办 oracle11g如何正确安装配置EM
    oracle不能使用EM的解决方法,具体内容如下 不能登录EM,执行emca -config dbcontrol db 不知道总是默认1522的端口号,无奈,google一番,从下面第二步开始执行。。。(...
    99+
    2022-10-18
  • python3安装和使用virtuale
    本文介绍了virtualenv的安装,以及使用virtualenvwrapper提高效率。本文的操作示例是在linux下完成。 一. 安装 前提: python3和pip3都已经安装。 [root@localhost]# pip3 ...
    99+
    2023-01-31
    virtuale
  • Python使用poplib模块和smtplib模块收发电子邮件的教程
    poplib模块接收邮件 python的poplib模块是用来从pop3收取邮件的,也可以说它是处理邮件的第一步。 POP3协议并不复杂,它也是采用的一问一答式的方式,你向服务器发送一个命令,服务器必然会回...
    99+
    2022-06-04
    模块 收发电子邮件 教程
  • CSS长度单位em怎么使用
    本篇内容介绍了“CSS长度单位em怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!   ...
    99+
    2022-10-19
  • html长度单位EM怎么使用
    本文小编为大家详细介绍“html长度单位EM怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“html长度单位EM怎么使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。 ...
    99+
    2022-10-19
  • Python3 turtle安装和使用教
    Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x、纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,从而在它爬行的路径上绘制了图形。 1 安装turtl...
    99+
    2023-01-31
    turtle
  • Python如何使用email、smtplib、poplib、imaplib模块收发邮件
    一封电子邮件的旅程是:Mail User Agent (MUA) refers to an email client or software used by a user to access their email account.。(即类...
    99+
    2023-05-17
    Python email smtplib
  • css中em相对单位怎么使用
    本篇内容介绍了“css中em相对单位怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!   em是C...
    99+
    2022-10-19
  • python3——print使用
        print的初步认识:对于科班出身的或有相关经验的人来说,学习python是相当有趣的事,因为可以做日常任务,比如自动备份你的MP3;可以做网站,如YouTube就是Python写的;可以做网络游戏的后台,很多在线游戏的后台都是P...
    99+
    2023-01-31
    print
  • python3 使用 asyncio
    python3提供了协程专用的关键字async await, 还提供了asyncio库, 来进行异步非阻塞的io操作 异步非阻塞的io操作 没有老师检查我也不知道自己算不算完全懂了, 就不做无用功尝试说得通俗易懂了.想要从原理开始理解的话...
    99+
    2023-01-31
    asyncio
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作