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

第一段代码:

代码如下:

#!/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 = 'username@somehost.com'
        toAdd = ['someone@somehost.com', 'other@somehost.com']
        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()

(0)

相关推荐

  • python发送邮件示例(支持中文邮件标题)

    复制代码 代码如下: def sendmail(login={},mail={}):    '''\    @param login login['user'] login['passwd']    @param mail mail['to_addr'] mail['subject'] mail['content'] mail['attach']    '''    from datetime import datetime    from base64 import b64encode   

  • python发送邮件接收邮件示例分享

    接收邮件 复制代码 代码如下: import poplib,pdb,email,re,timefrom email import header POP_ADDR = r'pop.126.com'USER = ''PASS = ''CONFIG = '' def getYear(date):    rslt = re.search(r'\b2\d{3}\b', date)    return int(rslt.group()) def getMonth(date):    monthMap = {

  • python中使用smtplib和email模块发送邮件实例

    SMTP模块 这么多已定义的类中,我们最常用的的还是smtplib.SMTP类,就具体看看该类的用法:smtp实例封装一个smtp连接,它支持所有的SMTP和ESMTP操作指令,如果host和port参数被定义,则smtp会在初始化期间自动调用connect()方法,如果connect()方法失败,则会触发SMTPConnectError异常,timeout参数设置了超时时间.在一般的调用过程中,应该遵connetc().sendmail().quit()步骤. SMTP模块主要方法 下面我们来

  • 基于python发送邮件的乱码问题的解决办法

    公司项目中需要通过后台发送邮件,邮件内容包括图片附件.如果通过PHPmailer发送,由于邮件服务器可能存在延迟现象,通过PHPmailer发送邮件,需要等待邮件发送成功后才能返回结果,这在实践中证明,有时发送邮件无法即时返回结果,影响用户体验. 于是我通过python发送邮件,PHP通过调用脚本方式来调用,这样执行脚本成功后立即返回,而无需判断邮件是否发送成功.只要成功执行脚本文件即向客户端返回成功标志.这样极大的提高了邮件发送速度,保证良好的用户体验效果. 但是,在通过python发送邮件,

  • 二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)

    可以使用Python的email模块来实现带有附件的邮件的发送. SMTP (Simple Mail Transfer Protocol)邮件传送代理 (Mail Transfer Agent,MTA) 程序使用SMTP协议来发送电邮到接收者的邮件服务器.SMTP协议只能用来发送邮件,不能用来接收邮件.大多数的邮件发送服务器 (Outgoing Mail Server) 都是使用SMTP协议.SMTP协议的默认TCP端口号是25. SMTP协议的一个重要特点是它能够接力传送邮件.它工作在两种情况

  • python同时给两个收件人发送邮件的方法

    本文实例讲述了python同时给两个收件人发送邮件的方法.分享给大家供大家参考.具体分析如下: 该范例通过python内置的smtplib包发送邮件 import smtplib import string host = "localhost" fromclause = "a@b.com" toclause = "c@d.com, e@f.com" toclause = string.splitfields(toclause, ",&q

  • python使用SMTP发送qq或sina邮件

    python使用qq邮箱(个人邮箱)发送邮件需开启qq邮箱的SMTP服务 在设置中开启pop3/SMTP服务,返回的密码就是之后代码中登录使用账户密码(在完整代码中标识了出来) 之后出现如下错误 复制代码 代码如下: smtplib.SMTPAuthenticationError: (530, 'Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/

  • python监控网站运行异常并发送邮件的方法

    本文实例讲述了python监控网站运行异常并发送邮件的方法.分享给大家供大家参考.具体如下: 这是一个简单的python开发的监控程序,当指定网页状态不正常是通过smtp发送通知邮件 复制代码 代码如下: #!/usr/bin/env python # -*- coding: UTF-8 -*- #author  libertyspy import socket import smtplib import urllib mail_options = {     'server':'smtp.qq

  • Python实现给qq邮箱发送邮件的方法

    本文实例讲述了Python实现给qq邮箱发送邮件的方法.分享给大家供大家参考.具体实现方法如下: #-*-coding:utf-8-*- #========================================== # 导入smtplib和MIMEText #========================================== from email.mime.text import MIMEText import smtplib #===================

  • Python实现SMTP发送邮件详细教程

    简介 Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后面找了很久才找到原因,这都是没有一个详细的环境调试导致,所以今天特出一个详细的教程,一步一步从环境调试到代码实现整一个教程,希望对还在苦苦寻找解决方法却迟迟不能得到有效解决的人员一点帮助. SMTP协议 首先了解SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器.SMTP协议只能用来发送邮件,不能用

随机推荐