python发送邮件的实例代码(支持html、图片、附件)

转自http://www.jb51.net/article/34498.htm

第一段代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText):

strFrom = fromAdd
        strTo = ‘, ‘.join(toAdd)

server = authInfo.get(‘server‘)
        user = authInfo.get(‘user‘)
        passwd = authInfo.get(‘password‘)

if not (server and user and passwd) :
                print ‘incomplete login info, exit now‘
                return

# 设定root信息
        msgRoot = MIMEMultipart(‘related‘)
        msgRoot[‘Subject‘] = subject
        msgRoot[‘From‘] = strFrom
        msgRoot[‘To‘] = strTo
        msgRoot.preamble = ‘This is a multi-part message in MIME format.‘

# Encapsulate the plain and HTML versions of the message body in an
        # ‘alternative‘ part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart(‘alternative‘)
        msgRoot.attach(msgAlternative)

#设定纯文本信息
        msgText = MIMEText(plainText, ‘plain‘, ‘utf-8‘)
        msgAlternative.attach(msgText)

#设定HTML信息
        msgText = MIMEText(htmlText, ‘html‘, ‘utf-8‘)
        msgAlternative.attach(msgText)

#设定内置图片信息
        fp = open(‘test.jpg‘, ‘rb‘)
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header(‘Content-ID‘, ‘<image1>‘)
        msgRoot.attach(msgImage)

#发送邮件
        smtp = smtplib.SMTP()
       #设定调试级别,依情况而定
        smtp.set_debuglevel(1)
        smtp.connect(server)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, strTo, msgRoot.as_string())
        smtp.quit()
        return

if __name__ == ‘__main__‘ :
        authInfo = {}
        authInfo[‘server‘] = ‘smtp.somehost.com‘
        authInfo[‘user‘] = ‘username‘
        authInfo[‘password‘] = ‘password‘
        fromAdd = ‘[email protected]‘
        toAdd = [‘[email protected]‘, ‘[email protected]‘]
        subject = ‘邮件主题‘
        plainText = ‘这里是普通文本‘
        htmlText = ‘<B>HTML文本</B>‘
        sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)

文件形式的邮件

#!/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()

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>你好</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()

带图片的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.image 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 image.<br><img src="cid:image1"><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‘, ‘<image1>‘)
msgRoot.attach(msgImage)

smtp = smtplib.SMTP()
smtp.connect(‘smtp.163.com‘)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()

带附件的邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image 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"] = ‘attachment; 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()

群邮件

#!/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(‘你好‘,‘plain‘,‘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()

各种元素都包含的邮件

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image 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"] = ‘attachment; 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()

基于SSL的邮件

#!/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(‘你好‘,‘plain‘,‘utf-8‘)#中文需参数‘utf-8‘,单字节字符不需要
msg[‘Subject‘] = Header(subject, ‘utf-8‘)

smtp = smtplib.SMTP()
smtp.connect(‘smtp.163.com‘)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.set_debuglevel(1)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

时间: 2024-10-17 18:10:53

python发送邮件的实例代码(支持html、图片、附件)的相关文章

Python操作Mysql实例代码教程在线版(查询手册)_python

实例1.取得MYSQL的版本 在windows环境下安装mysql模块用于python开发 MySQL-python Windows下EXE安装文件下载 复制代码 代码如下: # -*- coding: UTF-8 -*- #安装MYSQL DB for pythonimport MySQLdb as mdb con = None try:    #连接mysql的方法:connect('ip','user','password','dbname')    con = mdb.connect('

Python中文转拼音代码(支持全拼和首字母缩写)

本文的代码,从https://github.com/cleverdeng/pinyin.py升级得来,针对原文的代码,做了以下升级: 1 2 3 4 1.可以传入参数firstcode:如果为true,只取汉子的第一个拼音字母:如果为false,则会输出全部拼音: 2.修复:如果为英文字母,则直接输出: 3.修复:如果分隔符为空字符串,仍然能正常输出: 4.升级:可以指定词典的文件路径 代码很简单,直接读取了一个词典(字符和英文的映射),然后挨个替换中文中的拼音即可: Python 1 2 3

Python操作Mysql实例代码

实例1.取得MYSQL的版本在windows环境下安装mysql模块用于python开发 MySQL-python Windows下EXE安装文件下载 代码如下: # -*- coding: UTF-8 -*- #安装MYSQL DB for pythonimport MySQLdb as mdb con = None try:    #连接mysql的方法:connect('ip','user','password','dbname')    con = mdb.connect('localh

python发送邮件(qq)

在即时通信软件如此发达的今天,电子邮件仍然是互联网上使用最为广泛的应用之一,公司向应聘者发出录用通知.网站向用户发送一个激活账号的链接.银行向客户推广它们的理财产品等几乎都是通过电子邮件来完成的,而这些任务应该都是由程序自动完成的. 就像我们可以用HTTP(超文本传输协议)来访问一个网站一样,发送邮件要使用SMTP(简单邮件传输协议),SMTP也是一个建立在TCP(传输控制协议)提供的可靠数据传输服务的基础上的应用级协议,它规定了邮件的发送者如何跟发送邮件的服务器进行通信的细节,而Python中

Python文件和目录操作实例代码

对于文件和目录的处理,虽然可以通过操作系统命令来完成,但是Python语言为了便于开发人员以编程的方式处理相关工作,提供了许多处理文件和目录的内置函数.重要的是,这些函数无论是在Unix.Windows还是Macintosh平台上,它们的使用方式是完全一致的. 本文将详细解释这些函数的使用方法.首先,介绍Python语言中类似于Windows系统的dir命令的列出文件功能,然后描述如何测试一个文件名对应的是一个标准文件.目录还是链接,以及提取文件大小和日期的方法.之后,还将介绍如何删除文件和目录

【转载】python发送邮件实例

本文转自:http://www.cnblogs.com/lonelycatcher/archive/2012/02/09/2343463.html 这几天要用python发送邮件,上网找到这篇文章感觉蛮全面的,故转载收藏之. 1. 文件形式的邮件 #!/usr/bin/env python3 #coding: utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header send

Python连接MySQL的实例代码

Python连接MySQL的实例代码 MySQLdb下载地址:http://sourceforge.net/projects/mysql-python/ 下载解压缩后放到%Python_HOME%/Lib/site-packages目录中,python会自动找到此包. MySQLdb基本上是MySQL C API的Python版,遵循Python Database API Specification v2.0. 其他: 1. 平台及版本 linux 内核2.6,gcc 3.4.4,glibc 2

PHP加水印代码 支持文字和图片水印

PHP加图片水印.文字水印类代码,PHP加水印类,支持文字图片水印的透明度设置.水印图片背景透明.自己写的一个类,因为自己开发的一套CMS中要用到,网上的总感觉用着不顺手,希望大家也喜欢这个类,后附有类使用方法. <?php class WaterMask{ public $waterType = 1; //水印类型:0为文字水印.1为图片水印 public $pos = 0; //水印位置 public $transparent = 45; //水印透明度 public $waterStr =

CSS实现的鼠标经过链接切换背景图片实例代码

CSS实现的鼠标经过链接切换背景图片实例代码:很多导航栏都有这样的效果,当鼠标滑过的时候能够实现背景图片的切换,算是一个比较好的效果吧,也算是对导航栏最基本的美化了.代码实例如下: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="