Python發送郵件(常見四種郵件內容)
阿新 • • 發佈:2017-11-25
t對象 3.6 idt serve ttl dddd python tdi tls
[python] view plain copy
Python發送郵件(常見四種郵件內容)
轉載 2017年03月03日 17:17:04轉自: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()
[python] view plain copy
- >>> 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)
- {}
進入騰訊和網易收件人郵箱,就能看到剛發的測試郵件,一般都被郵箱服務器過濾成垃圾郵件,所以收件箱沒有,你要去垃圾箱看看。
[python] view plain copy
- >>> 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‘)
[python] view plain copy
- >>> 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發送郵件(常見四種郵件內容)