Python发送邮件(常见四种邮件内容)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python发送邮件(常见四种邮件内容)相关的知识,希望对你有一定的参考价值。
Python发送邮件(常见四种邮件内容)
转自:http://lizhenliang.blog.51cto.com/7876557/1875330
SMTP.set_debuglevel(level) | 设置输出debug调试信息,默认不输出 |
SMTP.docmd(cmd[, argstring]) | 发送一个命令到SMTP服务器 |
SMTP.connect([host[, port]]) | 连接到指定的SMTP服务器 |
SMTP.helo([hostname]) | 使用helo指令向SMTP服务器确认你的身份 |
SMTP.ehlo(hostname) | 使用ehlo指令像ESMTP(SMTP扩展)确认你的身份 |
SMTP.ehlo_or_helo_if_needed() | 如果在以前的会话连接中没有提供ehlo或者helo指令,这个方法会调用ehlo()或helo() |
SMTP.has_extn(name) | 判断指定名称是否在SMTP服务器上 |
SMTP.verify(address) | 判断邮件地址是否在SMTP服务器上 |
SMTP.starttls([keyfile[, certfile]]) | 使SMTP连接运行在TLS模式,所有的SMTP指令都会被加密 |
SMTP.login(user, password) | 登录SMTP服务器 |
SMTP.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]) | |
SMTP.quit() | 关闭SMTP会话 |
SMTP.close() | 关闭SMTP服务器连接 |
- >>> import smtplib
- >>> s=smtplib.SMTP("localhost")
- >>> tolist=["[email protected]","[email protected]","[email protected]","[email protected]"]
- >>> msg = ‘‘‘‘‘\
- ... From: [email protected]
- ... Subject: testin‘...
- ...
- ... This is a test ‘‘‘
- >>> s.sendmail("[email protected]",tolist,msg)
- { "[email protected]" : ( 550 ,"User unknown" ) }
- >>> s.quit()
- >>> import smtplib
- >>> s = smtplib.SMTP("localhost")
- >>> tolist = ["[email protected]", "[email protected]"]
- >>> msg = ‘‘‘‘‘\
- ... From: [email protected]
- ... Subject: test
- ... This is a test ‘‘‘
- >>> s.sendmail("[email protected]", tolist, msg)
- {}
进入腾讯和网易收件人邮箱,就能看到刚发的测试邮件,一般都被邮箱服务器过滤成垃圾邮件,所以收件箱没有,你要去垃圾箱看看。
- >>> import smtplib
- >>> s = smtplib.SMTP("smtp.163.com")
- >>> s.login("[email protected]", "xxx")
- (235, ‘Authentication successful‘)
- >>> tolist = ["[email protected]", "[email protected]"]
- >>> msg = ‘‘‘‘‘\
- ... From: [email protected]
- ... Subject: test
- ... This is a test ‘‘‘
- >>> s.sendmail("[email protected]", tolist, msg)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "/usr/lib64/python2.6/smtplib.py", line 725, in sendmail
- raise SMTPDataError(code, resp)
- smtplib.SMTPDataError: (554, ‘DT:SPM 163 smtp10,DsCowAAXIdDIJAtYkZiTAA--.65425S2 1477125592,please see http://mail.163.com/help/help_spam_16.htm?ip=119.57.73.67&hostid=smtp10&time=1477125592‘)
- >>> msg = ‘‘‘‘‘\
- ... From: [email protected]
- ... To: [email protected] ,[email protected]
- ... Subject: test
- ...
- ... This is a test ‘‘‘
- >>> s.sendmail("[email protected]", tolist, msg)
- {}
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import smtplib
- def sendMail(body):
- smtp_server = ‘smtp.163.com‘
- from_mail = ‘[email protected]‘
- mail_pass = ‘xxx‘
- to_mail = [‘[email protected]‘, ‘[email protected]‘]
- cc_mail = [‘[email protected]‘]
- from_name = ‘monitor‘
- subject = u‘监控‘.encode(‘gbk‘) # 以gbk编码发送,一般邮件客户端都能识别
- # msg = ‘‘‘\
- # From: %s <%s>
- # To: %s
- # Subject: %s
- # %s‘‘‘ %(from_name, from_mail, to_mail_str, subject, body) # 这种方式必须将邮件头信息靠左,也就是每行开头不能用空格,否则报SMTP 554
- mail = [
- "From: %s <%s>" % (from_name, from_mail),
- "To: %s" % ‘,‘.join(to_mail), # 转成字符串,以逗号分隔元素
- "Subject: %s" % subject,
- "Cc: %s" % ‘,‘.join(cc_mail),
- "",
- body
- ]
- msg = ‘\n‘.join(mail) # 这种方式先将头信息放到列表中,然后用join拼接,并以换行符分隔元素,结果就是和上面注释一样了
- try:
- s = smtplib.SMTP()
- s.connect(smtp_server, ‘25‘)
- s.login(from_mail, mail_pass)
- s.sendmail(from_mail, to_mail+cc_mail, msg)
- s.quit()
- except smtplib.SMTPException as e:
- print "Error: %s" %e
- if __name__ == "__main__":
- sendMail("This is a test!")
- message = Message()
- message[‘Subject‘] = ‘邮件主题‘
- message[‘From‘] = from_mail
- message[‘To‘] = to_mail
- message[‘Cc‘] = cc_mail
- message.set_payload(‘邮件内容‘)
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import smtplib
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- from email.header import Header
- from email import encoders
- from email.mime.base import MIMEBase
- from email.utils import parseaddr, formataddr
- # 格式化邮件地址
- def formatAddr(s):
- name, addr = parseaddr(s)
- return formataddr((Header(name, ‘utf-8‘).encode(), addr))
- def sendMail(body, attachment):
- smtp_server = ‘smtp.163.com‘
- from_mail = ‘[email protected]‘
- mail_pass = ‘xxx‘
- to_mail = [‘[email protected]‘, ‘[email protected]‘]
- # 构造一个MIMEMultipart对象代表邮件本身
- msg = MIMEMultipart()
- # Header对中文进行转码
- msg[‘From‘] = formatAddr(‘管理员 <%s>‘ % from_mail).encode()
- msg[‘To‘] = ‘,‘.join(to_mail)
- msg[‘Subject‘] = Header(‘监控‘, ‘utf-8‘).encode()
- # plain代表纯文本
- msg.attach(MIMEText(body, ‘plain‘, ‘utf-8‘))
- # 二进制方式模式文件
- with open(attachment, ‘rb‘) as f:
- # MIMEBase表示附件的对象
- mime = MIMEBase(‘text‘, ‘txt‘, filename=attachment)
- # filename是显示附件名字
- mime.add_header(‘Content-Disposition‘, ‘attachment‘, filename=attachment)
- # 获取附件内容
- mime.set_payload(f.read())
- encoders.encode_base64(mime)
- # 作为附件添加到邮件
- msg.attach(mime)
- try:
- s = smtplib.SMTP()
- s.connect(smtp_server, "25")
- s.login(from_mail, mail_pass)
- s.sendmail(from_mail, to_mail, msg.as_string()) # as_string()把MIMEText对象变成str
- s.quit()
- except smtplib.SMTPException as e:
- print "Error: %s" % e
- if __name__ == "__main__":
- sendMail(‘附件是测试数据, 请查收!‘, ‘test.txt‘)
3 Python发送HTML邮件
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import smtplib
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- from email.header import Header
- from email.utils import parseaddr, formataddr
- # 格式化邮件地址
- def formatAddr(s):
- name, addr = parseaddr(s)
- return formataddr((Header(name, ‘utf-8‘).encode(), addr))
- def sendMail(body):
- smtp_server = ‘smtp.163.com‘
- from_mail = ‘[email protected]‘
- mail_pass = ‘xxx‘
- to_mail = [‘[email protected]‘, ‘[email protected]‘]
- # 构造一个MIMEMultipart对象代表邮件本身
- msg = MIMEMultipart()
- # Header对中文进行转码
- msg[‘From‘] = formatAddr(‘管理员 <%s>‘ % from_mail).encode()
- msg[‘To‘] = ‘,‘.join(to_mail)
- msg[‘Subject‘] = Header(‘监控‘, ‘utf-8‘).encode()
- msg.attach(MIMEText(body, ‘html‘, ‘utf-8‘))
- try:
- s = smtplib.SMTP()
- s.connect(smtp_server, "25")
- s.login(from_mail, mail_pass)
- s.sendmail(from_mail, to_mail, msg.as_string()) # as_string()把MIMEText对象变成str
- s.quit()
- except smtplib.SMTPException as e:
- print "Error: %s" % e
- if __name__ == "__main__":
- body = """
- <h1>测试邮件</h1>
- <h2 style="color:red">This is a test</h1>
- """
- sendMail(body)
4 Python发送图片邮件
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import smtplib
- from email.mime.text import MIMEText
- from email.mime.image import MIMEImage
- from email.mime.multipart import MIMEMultipart
- from email.header import Header
- from email.utils import parseaddr, formataddr
- # 格式化邮件地址
- def formatAddr(s):
- name, addr = parseaddr(s)
- return formataddr((Header(name, ‘utf-8‘).encode(), addr))
- def sendMail(body, image):
- smtp_server = ‘smtp.163.com‘
- from_mail = ‘[email protected]‘
- mail_pass = ‘xxx‘
- to_mail = [‘[email protected]‘, ‘[email protected]‘]
- # 构造一个MIMEMultipart对象代表邮件本身
- msg = MIMEMultipart()
- # Header对中文进行转码
- msg[‘From‘] = formatAddr(‘管理员 <%s>‘ % from_mail).encode()
- msg[‘To‘] = ‘,‘.join(to_mail)
- msg[‘Subject‘] = Header(‘监控‘, ‘utf-8‘).encode()
- msg.attach(MIMEText(body, ‘html‘, ‘utf-8‘))
- # 二进制模式读取图片
- with open(image, ‘rb‘) as f:
- msgImage = MIMEImage(f.read())
- # 定义图片ID
- msgImage.add_header(‘Content-ID‘, ‘<image1>‘)
- msg.attach(msgImage)
- try:
- s = smtplib.SMTP()
- s.connect(smtp_server, "25")
- s.login(from_mail, mail_pass)
- s.sendmail(from_mail, to_mail, msg.as_string()) # as_string()把MIMEText对象变成str
- s.quit()
- except smtplib.SMTPException as e:
- print "Error: %s" % e
- if __name__ == "__main__":
- body = """
- <h1>测试图片</h1>
- <img src="cid:image1"/> # 引用图片
- """
- sendMail(body, ‘test.png‘)
上面发邮件的几种常见的发邮件方法基本满足日常需求了。
以上是关于Python发送邮件(常见四种邮件内容)的主要内容,如果未能解决你的问题,请参考以下文章