導航:首頁 > 編程語言 > 郵件自動發送python

郵件自動發送python

發布時間:2022-04-15 01:32:17

㈠ 利用python實現定時發送郵件功能,有大神么

一、文件形式的郵件 復制代碼 代碼如下: #!/usr/bin/env python3 #coding: utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header sender = '***' receiver = '***' subject = 'python email test' smtps...

㈡ python中如何實現發送郵件及附件功能的具體詳解

思路如下:
1. 構造MIMEMultipart對象做為根容器
2. 構造MIMEText對象做為郵件顯示內容並附加到根容器
3. 構造MIMEBase對象做為文件附件內容並附加到根容器
a. 讀入文件內容並格式化
b. 設置附件頭
4. 設置根容器屬性
5. 得到格式化後的完整文本
6. 用smtp發送郵件

㈢ 如何用python發送email

python中email模塊使得處理郵件變得比較簡單,今天著重學習了一下發送郵件的具體做法,這里寫寫自己的的心得,也請高手給些指點。
一、相關模塊介紹
發送郵件主要用到了smtplib和email兩個模塊,這里首先就兩個模塊進行一下簡單的介紹:
1、smtplib模塊
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP類構造函數,表示與SMTP伺服器之間的連接,通過這個連接可以向smtp伺服器發送指令,執行相關操作(如:登陸、發送郵件)。所有參數都是可選的。
host:smtp伺服器主機名
port:smtp服務的埠,默認是25;如果在創建SMTP對象的時候提供了這兩個參數,在初始化的時候會自動調用connect方法去連接伺服器。
smtplib模塊還提供了SMTP_SSL類和LMTP類,對它們的操作與SMTP基本一致。
smtplib.SMTP提供的方法:
SMTP.set_debuglevel(level):設置是否為調試模式。默認為False,即非調試模式,表示不輸出任何調試信息。
SMTP.connect([host[, port]]):連接到指定的smtp伺服器。參數分別表示smpt主機和埠。注意: 也可以在host參數中指定埠號(如:smpt.yeah.net:25),這樣就沒必要給出port參數。
SMTP.docmd(cmd[, argstring]):向smtp伺服器發送指令。可選參數argstring表示指令的參數。
SMTP.helo([hostname]) :使用"helo"指令向伺服器確認身份。相當於告訴smtp伺服器「我是誰」。
SMTP.has_extn(name):判斷指定名稱在伺服器郵件列表中是否存在。出於安全考慮,smtp伺服器往往屏蔽了該指令。
SMTP.verify(address) :判斷指定郵件地址是否在伺服器中存在。出於安全考慮,smtp伺服器往往屏蔽了該指令。
SMTP.login(user, password) :登陸到smtp伺服器。現在幾乎所有的smtp伺服器,都必須在驗證用戶信息合法之後才允許發送郵件。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :發送郵件。這里要注意一下第三個參數,msg是字元串,表示郵件。我們知道郵件一般由標題,發信人,收件人,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。
SMTP.quit() :斷開與smtp伺服器的連接,相當於發送"quit"指令。(很多程序中都用到了smtp.close(),具體與quit的區別google了一下,也沒找到答案。)
2、email模塊
emial模塊用來處理郵件消息,包括MIME和其他基於RFC 2822 的消息文檔。使用這些模塊來定義郵件的內容,是非常簡單的。其包括的類有:
class email.mime.base.MIMEBase(_maintype, _subtype, **_params):這是MIME的一個基類。一般不需要在使用時創建實例。其中_maintype是內容類型,如text或者image。_subtype是內容的minor type 類型,如plain或者gif。 **_params是一個字典,直接傳遞給Message.add_header()。
class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]:MIMEBase的一個子類,多個MIME對象的集合,_subtype默認值為mixed。boundary是MIMEMultipart的邊界,默認邊界是可數的。
class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):MIMEMultipart的一個子類。
class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音頻對象
class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):MIME二進制文件對象。
class email.mime.message.MIMEMessage(_msg[, _subtype]):具體的一個message實例,使用方法如下:

msg=mail.Message.Message() #一個實例
msg['to']='[email protected]' #發送到哪裡
msg['from']='[email protected]' #自己的郵件地址
msg['date']='2012-3-16' #時間日期
msg['subject']='hello world' #郵件主題

class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):MIME文本對象,其中_text是郵件內容,_subtype郵件類型,可以是text/plain(普通文本郵件),html/plain(html郵件), _charset編碼,可以是gb2312等等。
二、幾種郵件的具體實現代碼
1、普通文本郵件
普通文本郵件發送的實現,關鍵是要將MIMEText中_subtype設置為plain。首先導入smtplib和mimetext。創建smtplib.smtp實例,connect郵件smtp伺服器,login後發送,具體代碼如下:(python2.6下實現)

# -*- coding: UTF-8 -*-
'''
發送txt文本郵件
小五義:
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=[[email protected]]
mail_host="smtp.XXX.com" #設置伺服器
mail_user="XXXX" #用戶名
mail_pass="XXXXXX" #口令
mail_postfix="XXX.com" #發件箱的後綴

def send_mail(to_list,sub,content):
me="hello"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","hello world!"):
print "發送成功"
else:
print "發送失敗"

2、html郵件的發送
與text郵件不同之處就是將將MIMEText中_subtype設置為html。具體代碼如下:(python2.6下實現)

# -*- coding: utf-8 -*-
'''
發送html文本郵件

'''
import smtplib
from email.mime.text import MIMEText
mailto_list=["[email protected]"]
mail_host="smtp.XXX.com" #設置伺服器
mail_user="XXX" #用戶名
mail_pass="XXXX" #口令
mail_postfix="XXX.com" #發件箱的後綴

def send_mail(to_list,sub,content): #to_list:收件人;sub:主題;content:郵件內容
me="hello"+"<"+mail_user+"@"+mail_postfix+">" #這里的hello可以任意設置,收到信後,將按照設置顯示
msg = MIMEText(content,_subtype='html',_charset='gb2312') #創建一個實例,這里設置為html格式郵件
msg['Subject'] = sub #設置主題
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host) #連接smtp伺服器
s.login(mail_user,mail_pass) #登陸伺服器
s.sendmail(me, to_list, msg.as_string()) #發送郵件
s.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","<a href=''>小五義</a>"):
print "發送成功"
else:
print "發送失敗"

3、發送帶附件的郵件
發送帶附件的郵件,首先要創建MIMEMultipart()實例,然後構造附件,如果有多個附件,可依次構造,最後利用smtplib.smtp發送。

# -*- coding: cp936 -*-
'''
發送帶附件郵件

'''

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

#創建一個帶附件的實例
msg = MIMEMultipart()

#構造附件1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.doc"'#這里的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
msg.attach(att1)

#構造附件2
att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)

#加郵件頭
msg['to'] = '[email protected]'
msg['from'] = '[email protected]'
msg['subject'] = 'hello world'
#發送郵件
try:
server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXX')#XXX為用戶名,XXXXX為密碼
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print '發送成功'
except Exception, e:
print str(e)

4、利用MIMEimage發送圖片

# -*- coding: cp936 -*-
import smtplib
import mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def AutoSendMail():
msg = MIMEMultipart()
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = "hello world"

txt = MIMEText("這是中文的郵件內容哦",'plain','gb2312')
msg.attach(txt)

file1 = "C:\\hello.jpg"
image = MIMEImage(open(file1,'rb').read())
image.add_header('Content-ID','<image1>')
msg.attach(image)

server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXXX')
server.sendmail(msg['From'],msg['To'],msg.as_string())
server.quit()

if __name__ == "__main__":
AutoSendMail()

利用MIMEimage發送圖片,原本是想圖片能夠在正文中顯示,可是代碼運行後發現,依然是以附件形式發送的,希望有高手能夠指點一下,如何可以發送在正文中顯示的圖片的郵件,就是圖片是附件中存在,但同時能顯示在正文中,具體形式如下圖。

㈣ Python自動發送郵件多個人收件人代碼更改

msg['To'] = "[email protected];[email protected]" # 多個郵件接收者,中間用;隔開
msg['Cc'] = "[email protected];[email protected]" # 多個郵件抄送者,中間用;隔開

㈤ python 怎麼實現郵件發送

一般最好有個smtp伺服器,比如說你在163注冊個郵箱,這樣可以用smtplib通過這個郵箱來發送。以下是示例: #-*- coding:utf8 -*- import smtplib import email import mimetypes from email.MIMEMultipart import MIMEMultipart from email.mime....

㈥ 如何利用Python自動監控網站並發送郵件告警

1、監控網站

監控網站其實就是去爬網頁的源碼,每次對比或檢查網頁源碼特定位置的html代碼是否有變化即可,具體可以用

fromurllibimportrequest

page=request.urlopen("網址")
html=page.read()

就可以獲取網頁源碼;

2、發送高警

建議別用郵件,郵件發多幾次就會認為你的發件箱有發垃圾郵件的嫌疑。用 喵提醒 ,是個公眾號,可以免費發提醒到手機上。調用方法也和監控網頁代碼類似,具體自己看喵提醒的教程。

㈦ python 自動發郵件的方法怎麼寫

一、文件形式的郵件

復制代碼 代碼如下:
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

msg = MIMEText('你好','text','utf-8')#中文需參數『utf-8',單位元組字元不需要
msg['Subject'] = Header(subject, 'utf-8')

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

二、HTML形式的郵件

復制代碼 代碼如下:

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText

sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

msg = MIMEText('</pre>
<h1>你好</h1>
<pre>','html','utf-8')

msg['Subject'] = subject

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

三、帶圖片的HTML郵件

復制代碼 代碼如下:

#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'

msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.
<img alt="" src="cid:image1" />
good!','html','utf-8')
msgRoot.attach(msgText)

fp = open('h:\\python\\1.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

msgImage.add_header('Content-ID', '')
msgRoot.attach(msgImage)

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()

四、帶附件的郵件

復制代碼 代碼如下:
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'

#構造附件
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msgRoot.attach(att)

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()

五、群郵件

復制代碼 代碼如下:
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText

sender = '***'
receiver = ['***','****',……]
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

msg = MIMEText('你好','text','utf-8')

msg['Subject'] = subject

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

六、各種元素都包含的郵件

復制代碼 代碼如下:
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\

Hi!

How are you?

Here is the <a href="http://www.python.org">link</a> you wanted.

"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
#構造附件
att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msg.attach(att)

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

七、基於SSL的郵件

復制代碼 代碼如下:
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'

msg = MIMEText('你好','text','utf-8')#中文需參數『utf-8',單位元組字元不需要
msg['Subject'] = Header(subject, 'utf-8')

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.set_debuglevel(1)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

㈧ 如何用Python發郵件

一般最好有個smtp伺服器,比如說你在163注冊個郵箱,這樣可以用smtplib通過這個郵箱來發送。以下是示例:

#-*- coding:utf8 -*-
import smtplib
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.mime.text import MIMEText

mail_host="smtp.163.com"
mail_user="yourusername"
mail_pass="yourpassword"
mail_postfix="mail.163.com"

def sendmail(to_list,sub,con):
"""發送郵件
"""
# translation
me = mail_user+"<"+mail_user+"@"+mail_postfix+">"

msg = MIMEMultipart('related')
msg['Subject'] = email.Header.Header(sub,'utf-8')
msg['From'] = me
msg['To'] = ";".join(to_list)
msg.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgText = MIMEText(con, 'plain', 'utf-8')
msgAlternative.attach(msgText)
msg.attach(msgAlternative)

try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me, to_list, msg.as_string())
s.quit()

except Exception,e:
return False

return True

if __name__ == '__main__':
if sendmail(['[email protected]'],"測試","測試"):
print "Success!"
else:
print "Fail!"

如果要不經過郵件系統直接發,通常會被當作垃圾郵件扔了,所以還是這樣吧。

㈨ 如何使用python發郵件

直接貼點代碼,感受下

#!/usr/bin/python

#-*-coding:UTF-8-*-importsmtplib

fromemail.mime.textimportMIMEText

fromemail.headerimportHeadersender='XXXXX'
receivers=['[email protected]']#接收郵件,可設置為你的QQ郵箱或者其他郵箱#三個參數:第一個為文本內容,第二個plain設置文本格式,第三個utf-8設置編碼

message=MIMEText('Python郵件發送測試...','plain','utf-8')

message['From']=Header("測試",'utf-8')

message['To']=Header("測試",'utf-8')subject='PythonSMTP郵件測試'

message['Subject']=Header(subject,'utf-8')

try:

smtpObj=smtplib.SMTP('localhost')

smtpObj.sendmail(sender,receivers,message.as_string())

print"郵件發送成功"

exceptsmtplib.SMTPException:

print"Error:無法發送郵件"
閱讀全文

與郵件自動發送python相關的資料

熱點內容
java定義數據類型 瀏覽:874
安卓pdf手寫 瀏覽:427
什麼是app開發者 瀏覽:284
android鬧鍾重啟 瀏覽:101
程序員失職 瀏覽:518
在雲伺服器怎麼改密碼 瀏覽:586
伺服器pb什麼意思 瀏覽:940
51駕駛員的是什麼app 瀏覽:670
php靜態變數銷毀 瀏覽:886
編程買蘋果電腦 瀏覽:760
flac演算法 瀏覽:497
reactnative與android 瀏覽:663
程序員是干什麼的工作好嗎 瀏覽:258
kbuild編譯ko 瀏覽:469
條件編譯的宏 瀏覽:564
韓語編程語言 瀏覽:646
小程序開發如何租用伺服器 瀏覽:80
怎麼把釘釘文件夾保存到手機里 瀏覽:71
兵法pdf 瀏覽:645
app格式化下載不起怎麼辦 瀏覽:36