第一種是最常見的,smtp發(fā)送
import smtplib
import sys
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
def sendEmail(mail_sender, to_list, sub, content, attach_list = [], _subtype="html"):
"""
使用smtp發(fā)送郵件
:param mail_sender: 發(fā)件人
:param to_list: 收件人列表,用,間隔
:param sub: 主題
:param content: 內容
:param attach_list:附件
:param _subtype: 讀取內容用的方式,不傳html的話改成plain
:return:
"""
msg = MIMEMultipart()
msg['subject'] = sub
msg['From'] = mail_sender
msg['To'] = to_list
try:
msg.attach(MIMEText(content, _subtype,'utf-8')) #用html的方法是更方便于word文檔作為內容發(fā)送,可以先講word轉換成html,然后寫入其中
s = smtplib.SMTP('123.com', 25)
# s.login()
s.starttls()
if attach_list:
for att_path in attach_list:
path_arr = att_path.split(os.path.sep)
file_name = path_arr[len(path_arr) - 1]
att1 = MIMEText(open(att_path,'rb').read(), 'base64','utf-8')
att1.add_header('Content-Disposition', 'attachment', filename=file_name) #用這個方法可以避免附件亂碼
msg.attach(att1)
s.sendmail(mail_sender, to_list.split(u','), msg.as_string())
s.close()
print("999921||業(yè)務數據處理||郵件發(fā)送成功")
return True
except Exception as e:
sys.stderr.write("999931||{}".format(traceback.format_exc(limit=None, chain=True)))
sys.stderr.write("0001")
return False
第二種是用outlook發(fā)送的,這個大家借鑒使用文章來源:http://www.zghlxwxcb.cn/news/detail-601037.html
import os
from time import sleep
import autoit as au
import win32com.client
class OutlookUtills:
def __init__(self):
outlook = win32com.client.Dispatch("outlook.Application ")# outlook.Visible = True
self.mail = outlook.CreateItem(0)
self.mail.Display()
def sendEmail(self, addressee, subiect, AttachmentsPath=[], body=None):
"""
若body為默認值None則自動粘貼剪切板中內容進行發(fā)送
:param addressee: 收件人
:param subiect: 主題
:param AttachmentsPath: 附件名稱
:param body: 正文
:return:
"""
self.mail. To = addressee
self.mail.subject = subiect
if AttachmentsPath == []:
print("該郵件無附件")
else:
for Attachments in AttachmentsPath:
self.mail.Attachments.Add(Attachments)
print("地址:{},附件添加成功!!")
sleep(2)
if body == None:
self.mail.body = ""
au.send('^v')
print("正文已從剪切板拷貝")
else:
self.mail.body = body
print("正文由函數進行輸入")
sleep(1)
self.mail.Send()
if __name__ == '__main__':
my_outlook = OutlookUtills()
第三種是正文需要用到表格的,我在這里給大家一個示例,具體表格怎么改自行發(fā)揮文章來源地址http://www.zghlxwxcb.cn/news/detail-601037.html
import smtplib
from email.mime.text import MIMEText
from email.header import Header
class Mail:
def __init__(self):
# 第三方 SMTP 服務
self.mail_host = "smtp.qq.com" # 填寫郵箱服務器:這個是qq郵箱服務器,直接使用smtp.qq.com
self.mail_pass = "ahlwsnkajalubeif" # 填寫在qq郵箱設置中獲取的授權碼
self.sender = '1004983289@qq.com' # 填寫郵箱地址
self.receivers = ['tianyi.zhang@kingstarfintech.com'] # 填寫收件人的郵箱,QQ郵箱或者其他郵箱,可多個,中間用,隔開
def send(self):
self.mail_host = "smtp.qq.com" # 填寫郵箱服務器:這個是qq郵箱服務器,直接使用smtp.qq.com
self.mail_pass = "ahlwsnkajalubeif" # 填寫在qq郵箱設置中獲取的授權碼
self.sender = '1004983289@qq.com' # 填寫郵箱地址
self.receivers = ['tianyi.zhang@kingstarfintech.com'] # 填寫收件人的郵箱,QQ郵箱或者其他郵箱,可多個,中間用,隔開
insert = "<tr><td>152371200010240002</td><td>潘金蓮</td><td>tar</td><td>152371200010240002.tar</td><td>20220426-1545</td><td>否</td></tr><tr><td>152371200010240002</td><td>潘金蓮</td><td>tar</td><td>152371200010240002.tar</td><td>20220426-1545</td><td>否</td></tr>"
head = \
"""
<head>
<meta charset="utf-8">
<STYLE TYPE="text/css" MEDIA=screen>
table {
border-collapse: collapse;
border: 2px solid #a19da2;
/*居中顯示整個表格*/
margin: auto;
}
table thead {
border: 2px solid #91c6e1;
background: #f1f1f1;
padding: 10px 10px 10px 10px;
color: #333333;
}
table tbody {
border: 2px solid #91c6e1;
padding: 10px 10px 10px 10px;
}
table tr {
}
table th {
vertical-align: top;
font-size: 14px;
padding: 10px 10px 10px 10px;
color: #105de3;
font-family: arial;
text-align: center;
}
table td {
text-align: center;
padding: 10px 10px 10px 10px;
}
body {
font-family: 宋體;
}
h1 {
color: #5db446
}
div.header h2 {
color: #0002e3;
font-family: 黑體;
}
div.content h2 {
text-align: center;
font-size: 28px;
text-shadow: 2px 2px 1px #de4040;
color: #fff;
font-weight: bold;
background-color: #008eb7;
line-height: 1.5;
margin: 20px 0;
box-shadow: 10px 10px 5px #888888;
border-radius: 5px;
}
h3 {
font-size: 22px;
background-color: rgba(0, 2, 227, 0.71);
text-shadow: 2px 2px 1px #de4040;
color: rgba(239, 241, 234, 0.99);
line-height: 1.5;
}
h4 {
color: #e10092;
font-family: 楷體;
font-size: 20px;
text-align: center;
}
td img {
/*width: 60px;*/
max-width: 300px;
max-height: 300px;
}
</STYLE>
</head>
"""
body = \
"""
<body>
<div align="center" class="header">
<!--標題部分的信息-->
<h1 align="center">表格中的數據為當天云開戶信息下載及CRM上傳情況</h1>
</div>
<hr>
<div class="content">
<!--正文內容-->
<h2> </h2>
<div>
<h4></h4>
<table border="1" cellpadding="0" cellspacing="0" width="1600" style="border-collapse: collapse;">
<tbody>
<thead>
<tr><th>身份證號</th><th>姓名</th><th>文件類型</th><th>文件名</th><th>上傳時間</th><th>是否上傳成功</th></tr>
</thead>
<h2>掌廳不存在身份證不一致情況</h2>
</tbody>
</table>
</div>
<hr>
<p style="text-align: center">
</p>
</div>
</body>
""".format(insert)
html_msg = "<html>" + head + body + "</html>"
html_msg = html_msg.replace('\n', '').encode("utf-8")
message = MIMEText(html_msg, 'html', 'utf-8')
message['From'] = Header("小胖子xpp", 'utf-8') #郵件發(fā)送者姓名
message['To'] = Header("小胖子xpp", 'utf-8') #郵件接收者姓名
subject = '測試' #發(fā)送的主題
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(self.mail_host, 465) #建立smtp連接,qq郵箱必須用ssl邊接,因此邊接465端口
smtpObj.login(self.sender, self.mail_pass) #登陸
smtpObj.sendmail(self.sender, self.receivers, message.as_string()) #發(fā)送
smtpObj.quit()
print('發(fā)送成功!!')
except smtplib.SMTPException as e:
print('發(fā)送失敗??!')
if __name__ == '__main__':
mail = Mail()
mail.send()
到了這里,關于python發(fā)送郵件的幾種常用方法的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!