Python smtplib實(shí)現(xiàn)發(fā)送郵件功能
本文實(shí)例為大家分享了Python smtplib發(fā)送郵件功能的具體代碼,供大家參考,具體內(nèi)容如下
解決之前版本的問題,下面為最新版
#!/usr/bin/env python
# coding:gbk
"""
FuncName: sendemail.py
Desc: sendemail with text,image,audio,application...
Date: 2016-06-20 10:30
Home: http://blog.csdn.net/z_johnny
Author: johnny
"""
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import COMMASPACE
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
import ConfigParser
import smtplib
import os
class MyEmail:
def __init__(self, email_config_path, email_attachment_path):
"""
init config
"""
config = ConfigParser.ConfigParser()
config.read(email_config_path)
self.attachment_path = email_attachment_path
self.smtp = smtplib.SMTP()
self.login_username = config.get('SMTP', 'login_username')
self.login_password = config.get('SMTP', 'login_password')
self.sender = config.get('SMTP', 'login_username') # same as login_username
self.receiver = config.get('SMTP', 'receiver')
self.host = config.get('SMTP', 'host')
#self.port = config.get('SMTP', 'port') 發(fā)現(xiàn)加入端口后有時(shí)候發(fā)郵件出現(xiàn)延遲,故暫時(shí)取消
def connect(self):
"""
connect server
"""
#self.smtp.connect(self.host, self.port)
self.smtp.connect(self.host)
def login(self):
"""
login email
"""
try:
self.smtp.login(self.login_username, self.login_password)
except:
raise AttributeError('Can not login smtp!!!')
def send(self, email_title, email_content):
"""
send email
"""
msg = MIMEMultipart() # create MIMEMultipart
msg['From'] = self.sender # sender
receiver = self.receiver.split(",") # split receiver to send more user
msg['To'] = COMMASPACE.join(receiver)
msg['Subject'] = email_title # email Subject
content = MIMEText(email_content, _charset='gbk') # add email content ,coding is gbk, becasue chinese exist
msg.attach(content)
for attachment_name in os.listdir(self.attachment_path):
attachment_file = os.path.join(self.attachment_path,attachment_name)
with open(attachment_file, 'rb') as attachment:
if 'application' == 'text':
attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')
elif 'application' == 'image':
attachment = MIMEImage(attachment.read(), _subtype='octet-stream')
elif 'application' == 'audio':
attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')
else:
attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')
attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name))
# make sure "attachment_name is chinese" right
msg.attach(attachment)
self.smtp.sendmail(self.sender, receiver, msg.as_string()) # format msg.as_string()
def quit(self):
self.smtp.quit()
def send():
import time
ISOTIMEFORMAT='_%Y-%m-%d_%A'
current_time =str(time.strftime(ISOTIMEFORMAT))
email_config_path = './config/emailConfig.ini' # config path
email_attachment_path = './result' # attachment path
email_tiltle = 'johnny test'+'%s'%current_time # as johnny test_2016-06-20_Monday ,it can choose only file when add time
email_content = 'python發(fā)送郵件測(cè)試,包含附件'
myemail = MyEmail(email_config_path,email_attachment_path)
myemail.connect()
myemail.login()
myemail.send(email_tiltle, email_content)
myemail.quit()
if __name__ == "__main__":
# from sendemail import SendEmail
send()
配置文件emailConfig.ini
路徑要與程序?qū)?yīng)
;login_username : 登陸發(fā)件人用戶名 ;login_password : 登陸發(fā)件人密碼 ;host:port : 發(fā)件人郵箱對(duì)應(yīng)的host和端口,如:smtp.163.com:25 和 smtp.qq.com:465 ;receiver : 收件人,支持多方發(fā)送,格式(注意英文逗號(hào)): 123456789@163.com,zxcvbnm@qq.com [SMTP] login_username = johnny@163.com login_password = johnny host = smtp.163.com port = 25 receiver = johnny1@qq.com,johnny2@163.com,johnny3@gmail.com
之前版本出現(xiàn)的問題:
#!/usr/bin/env python
#coding: utf-8
'''''
FuncName: smtplib_email.py
Desc: 使用smtplib發(fā)送郵件
Date: 2016-04-11 14:00
Author: johnny
'''
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.utils import COMMASPACE,formatdate
from email import encoders
def send_email_text(sender,receiver,host,subject,text,filename):
assert type(receiver) == list
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = COMMASPACE.join(receiver)
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text)) #郵件正文內(nèi)容
for file in filename: #郵件附件
att = MIMEBase('application', 'octet-stream')
att.set_payload(open(file, 'rb').read())
encoders.encode_base64(att)
if file.endswith('.html'): # 若不加限定,jpg、html等格式附件是bin格式的
att.add_header('Content-Disposition', 'attachment; filename="今日測(cè)試結(jié)果.html"') # 強(qiáng)制命名,名稱未成功格式化,如果可以解決請(qǐng)聯(lián)系我
elif file.endswith('.jpg') or file.endswith('.png') :
att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"')
else:
att.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
msg.attach(att)
smtp = smtplib.SMTP(host)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(username,password)
smtp.sendmail(sender,receiver, msg.as_string())
smtp.close()
if __name__=="__main__":
sender = 'qqq@163.com'
receiver = ['www@qq.com']
subject = "測(cè)試"
text = "johnny'lab test"
filename = [u'測(cè)試報(bào)告.html','123.txt',u'獲取的信息.jpg']
host = 'smtp.163.com'
username = 'qqq@163.com'
password = 'qqq'
send_email_text(sender,receiver,host,subject,text,filename)
已測(cè)試通過,使用Header并沒有變成“頭”,故未使用
若能解決附件格式為(html、jpg、png)在郵箱附件中格式不為“bin”的請(qǐng)聯(lián)系我,希望此對(duì)大家有所幫助,謝謝(已解決,見上面最新版)
點(diǎn)擊查看:Python 郵件smtplib發(fā)送示例
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python中使用smtplib和email模塊發(fā)送郵件實(shí)例
- Python實(shí)現(xiàn)SMTP發(fā)送郵件詳細(xì)教程
- Python基于smtplib實(shí)現(xiàn)異步發(fā)送郵件服務(wù)
- 用smtplib和email封裝python發(fā)送郵件模塊類分享
- Python 使用SMTP發(fā)送郵件的代碼小結(jié)
- python3利用smtplib通過qq郵箱發(fā)送郵件方法示例
- python3實(shí)現(xiàn)163郵箱SMTP發(fā)送郵件
- python利用smtplib實(shí)現(xiàn)QQ郵箱發(fā)送郵件
- python3使用smtplib實(shí)現(xiàn)發(fā)送郵件功能
- python3實(shí)現(xiàn)SMTP發(fā)送郵件詳細(xì)教程
- Python基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能詳解
相關(guān)文章
python中如何使用xml.dom.minidom模塊讀取解析xml文件
xml.dom.minidom模塊應(yīng)該是內(nèi)置模塊不用下載安裝,本文給大家介紹python中如何使用xml.dom.minidom模塊讀取解析xml文件,感興趣的朋友一起看看吧2023-10-10
Python加載文件內(nèi)容的兩種實(shí)現(xiàn)方式
這篇文章主要介紹了Python加載文件內(nèi)容的兩種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Python讀取HDFS目錄下的所有文件的實(shí)現(xiàn)示例
HDFS是Apache Hadoop的分布式文件系統(tǒng),本文主要介紹了Python讀取HDFS目錄下的所有文件的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
pytorch_detach 切斷網(wǎng)絡(luò)反傳方式
這篇文章主要介紹了pytorch_detach 切斷網(wǎng)絡(luò)反傳方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-05-05
opencv-python 提取sift特征并匹配的實(shí)例
今天小編就為大家分享一篇opencv-python 提取sift特征并匹配的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12

