用smtplib和email封裝python發送郵件模組類分享

來源:互聯網
上載者:User
代碼如下:


#!/usr/bin/python
# encoding=utf-8
# Filename: send_email.py
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib


class SendEmail:
# 建構函式:初始化基本資料
def __init__(self, host, user, passwd):
lInfo = user.split("@")
self._user = user
self._account = lInfo[0]
self._me = self._account + "<" + self._user + ">"

server = smtplib.SMTP()
server.connect(host)
server.login(self._account, passwd)
self._server = server

# 傳送檔案或html郵件
def sendTxtMail(self, to_list, sub, content, subtype='html'):
# 如果發送的是文本郵件,則_subtype設定為plain
# 如果發送的是html郵件,則_subtype設定為html
msg = MIMEText(content, _subtype=subtype, _charset='utf-8')
msg['Subject'] = sub
msg['From'] = self._me
msg['To'] = ";".join(to_list)
try:
self._server.sendmail(self._me, to_list, msg.as_string())
return True
except Exception, e:
print str(e)
return False

# 發送帶附件的檔案或html郵件
def sendAttachMail(self, to_list, sub, content, subtype='html'):
# 建立一個帶附件的執行個體
msg = MIMEMultipart()
# 增加附件1
att1 = MIMEText(open(r'D:\javawork\PyTest\src\main.py','rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att1["Content-Disposition"] = 'attachment; filename="main.py"'
msg.attach(att1)

# 增加附件2
att2 = MIMEText(open(r'D:\javawork\PyTest\src\main.py','rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="main.txt"'
msg.attach(att2)

# 增加郵件內容
msg.attach(MIMEText(content, _subtype=subtype, _charset='utf-8'))

msg['Subject'] = sub
msg['From'] = self._me
msg['To'] = ";".join(to_list)

try:
self._server.sendmail(self._me, to_list, msg.as_string())
return True
except Exception, e:
print str(e)
return False
# 發送帶附件的檔案或html郵件
def sendImageMail(self, to_list, sub, content, subtype='html'):
# 建立一個帶附件的執行個體
msg = MIMEMultipart()

# 增加郵件內容
msg.attach(MIMEText(content, _subtype=subtype, _charset='utf-8'))

# 增加圖片附件
image = MIMEImage(open(r'D:\javawork\PyTest\src\test.jpg','rb').read())
#附件列表中顯示的檔案名稱
image.add_header('Content-Disposition', 'attachment;filename=p.jpg')
msg.attach(image)

msg['Subject'] = sub
msg['From'] = self._me
msg['To'] = ";".join(to_list)

try:
self._server.sendmail(self._me, to_list, msg.as_string())
return True
except Exception, e:
print str(e)
return False

# 解構函式:釋放資源
def __del__(self):
self._server.quit()
self._server.close()

mailto_list = ['xxx@163.com']
mail = SendEmail('smtp.163.com', 'xxx@163.com', 'xxxxxx')
if mail.sendTxtMail(mailto_list, "測試郵件", "hello world!

你好,發送文字檔測試

"):
print "發送成功"
else:
print "發送失敗"

if mail.sendAttachMail(mailto_list, "測試郵件-帶兩個附件", "hello world!

你好,發送文字檔測試

"):
print "發送成功"
else:
print "發送失敗"

if mail.sendImageMail(mailto_list, "測試郵件-帶一個圖片的附件", "hello world!

你好,發送文字檔測試

"):
print "發送成功"
else:
print "發送失敗"
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.