當前位置:首頁 » 編程語言 » python發送

python發送

發布時間: 2023-06-18 14:32:43

python批量發送郵件--包括批量不同附件

小豬在公司做出納,乾的活卻包括了出納、會計、結算專員等工作,周末都要被無奈在家加班,主要還沒有加班費,簡直是被公司嚴重壓榨。每個月初都要給每個工長發預付款賬單郵件,月中發結算款賬單。重復性機械工作。
一個及格線上的程序員,最起碼的覺悟就是將重復性的機械工作自動化,於是,在我花了一個多小時,幫她給一部分工長發了一次郵箱後,默默的回來寫了這個腳本
所以,設計要點就是一個字——
恩,就醬。

經過我觀察,郵件內容分為兩種,這里先說第一種,「結算款」:
(1) 郵件內容(content)不變,為固定的txt文本
(2) 附件(attch)為每個工長的結算賬單(excel文件.xlsx),此文件命名為總賬單中自動分割出來的名字(暫時不懂怎麼分割出來的=.=),格式為:

(3) 郵件主題(Subject)為附件名(不帶後綴名)
(4) 郵件接收對象(工長)的名單及其郵箱地址基本不變,偶爾變動
(5)

(1) 將工長及其郵箱地址存為CSV文件的兩列,python中將其讀取為字典形式,存儲以供後續查詢郵箱地址。

(2) 遍歷文件夾中的附件(.xlsx類型文件),對其進行兩種操作,一方面將其名字(不帶路徑和後綴)提取出來,作為郵件主題(Subject),並對Subject進一步劃分,得到其中的人名(工長);另一方面,將其傳入MIMEbase模塊中轉為郵件附件對象。

(3) 由上述得到的人名(name),在字典形式的通訊錄中,查找相應的地址(value),即為收件人名稱和地址
(4) 利用python中的email模塊和smtp模塊,登錄自己的郵箱賬號,再對每個附件,得到的收件人名和地址,添加附件,發送郵件。done

在設計過程中有幾點需要注意
(1) 有時一個郵件地址對應兩個人名,此時應該在CSV文件中分為兩行存儲,而不是將兩個人名存為同一個鍵;
(2)有賬單.xlsx文件,通訊錄里卻沒存儲此人記錄,程序應該列印提示沒有通訊記錄的人名,且不能直接退出,要保證員工看到此提示,此第一版程序還有解決此問題;
(3)此程序發送的郵件內容為純文本,若要求郵件內容有不同格式(如部分加粗,部分紅色),還有小部分需要每次更改的地方(如郵件內容包含當前月份),如何解決?(這就是第二種郵件內容,「預算款」);
(4)重名的,暫時還沒碰到,程序中也沒給出解決方案。

第一版到此,20180830,待更新
第二版更新,20180904

第三版更新,20180909

轉戰CSDN博客,更多博客見傳送門《 xiaozhou的博客主頁 》

② Python向多人發送、抄送帶附件的郵件(含詳細代碼)

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

步驟:

(1)設置伺服器所需信息(ps:部門郵箱密碼為授權碼,需自行登錄相應郵箱設置授權碼)

(2)設置email信息

(3)附件部分

(4)登錄郵箱並發送郵件

附上源碼

③ 如何用python發送email

python發送email還是比較簡單的,可以通過登錄郵件服務來發送,linux下也可以使用調用sendmail命令來發送,還可以使用本地或者是遠程的smtp服務來發送郵件,不管是單個,群發,還是抄送都比較容易實現。

先把幾個最簡單的發送郵件方式記錄下,像html郵件,附件等也是支持的,需要時查文檔即可

1 登錄郵件服務

[python]view plain

  • #!/usr/bin/envpython

  • #-*-coding:utf-8-*-

  • #python2.7x

  • #send_simple_email_by_account.py@2014-07-30

  • #author:orangleliu

  • '''''

  • 使用python寫郵件simple

  • 使用126的郵箱服務

  • '''

  • importsmtplib

  • fromemail.mime.textimportMIMEText

  • SMTPserver='smtp.126.com'

  • sender='[email protected]'

  • password="xxxx"

  • message='IsendamessagebyPython.你好'

  • msg=MIMEText(message)

  • msg['Subject']='TestEmailbyPython'

  • msg['From']=sender

  • msg['To']=destination

  • mailserver=smtplib.SMTP(SMTPserver,25)

  • mailserver.login(sender,password)

  • mailserver.sendmail(sender,[sender],msg.as_string())

  • mailserver.quit()

  • print'sendemailsuccess'

  • 2調用sendmail命令 (linux)

    [python]view plain

  • #-*-coding:utf-8-*-

  • #python2.7x

  • #send_email_by_.py

  • #author:orangleliu

  • #date:2014-08-15

  • '''''

  • 用的是sendmail命令的方式

  • 這個時候郵件還不定可以發出來,hostname配置可能需要更改

  • '''

  • fromemail.mime.textimportMIMEText

  • fromsubprocessimportPopen,PIPE

  • defget_sh_res():

  • p=Popen(['/Application/2.0/nirvana/logs/log.sh'],stdout=PIPE)

  • returnstr(p.communicate()[0])

  • defmail_send(sender,recevier):

  • print"getemailinfo..."

  • msg=MIMEText(get_sh_res())

  • msg["From"]=sender

  • msg["To"]=recevier

  • msg["Subject"]="Yestodayinterfacelogresults"

  • p=Popen(["/usr/sbin/sendmail","-t"],stdin=PIPE)

  • res=p.communicate(msg.as_string())

  • print'mailsended...'

  • if__name__=="__main__":

  • s="[email protected]"

  • r="[email protected]"

  • mail_send(s,r)

  • 3 使用smtp服務來發送(本地或者是遠程伺服器)

    [python]view plain

  • #!/usr/bin/envpython

  • #-*-coding:utf-8-*-

  • #python2.7x

  • #send_email_by_smtp.py

  • #author:orangleliu

  • #date:2014-08-15

  • '''''

  • linux下使用本地的smtp服務來發送郵件

  • 前提要開啟smtp服務,檢查的方法

  • #ps-ef|grepsendmail

  • #telnetlocalhost25

  • 這個時候郵件還不定可以發出來,hostname配置可能需要更改

  • '''

  • importsmtplib

  • fromemail.mime.textimportMIMEText

  • fromsubprocessimportPopen,PIPE

  • defget_sh_res():

  • p=Popen(['/Application/2.0/nirvana/logs/log.sh'],stdout=PIPE)

  • returnstr(p.communicate()[0])

  • defmail_send(sender,recevier):

  • msg=MIMEText(get_sh_res())

  • msg["From"]=sender

  • msg["To"]=recevier

  • msg["Subject"]="Yestodayinterfacelogresults"

  • s=smtplib.SMTP('localhost')

  • s.sendmail(sender,[recevier],msg.as_string())

  • s.quit()

  • print'sendmailfinished...'

  • if__name__=="__main__":

  • s="[email protected]"

  • r=s

  • mail_send(s,r)



④ python 發送簡訊

在電腦上用python給手機發簡訊我剛才試了,查了查資料,沒有想像中的那麼復雜:
1、在https://github.com/whtsky/PyWapFetion下載PyWapFetion文件
2、將PyWapFetion文件夾一起復制到自己的python,我用的是2.6版本,目錄C:\Python26\Lib\site-packages下
3、參照實例example.py寫上幾句,例如給自己發短息:
#!/usr/bin/python2.6
#
-*-
coding:
utf-8
-*-
from
__future__
import
with_statement
from
PyWapFetion
import
Fetion,
send2self,
send
send2self('自己手機號','飛信注冊密碼',"提示您")
4、一會兒就收到簡訊」提示您「了。

⑤ Python給指定微信好友自動發送信息和圖片

import os
import win32gui #pywin32-221.win-amd64-py3.7.exe
import win32con
from ctypes import *
import win32clipboard as w
import time
from PIL import Image #pip install pillow

import win32api

def setText(info):
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(win32con.CF_UNICODETEXT, info)
w.CloseClipboard()

def setImage(imgpath):
im = Image.open(imgpath)
im.save('1.bmp')
aString = windll.user32.LoadImageW(0, r"1.bmp", win32con.IMAGE_BITMAP, 0, 0, win32con.LR_LOADFROMFILE)

def m_click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

def pasteInfo():
win32api.keybd_event(17,0,0,0) #ctrl鍵位碼是17
win32api.keybd_event(86,0,0,0) #v鍵位碼是86
win32api.keybd_event(86,0,win32con.KEYEVENTF_KEYUP,0) #釋放按鍵
win32api.keybd_event(17,0,win32con.KEYEVENTF_KEYUP,0)

def searchByUser(uname):
hwnd = win32gui.FindWindow('WeChatMainWndForPC', '微信')
setText(uname)
m_click(100,40)
time.sleep(0.5)
m_click(100,40)
pasteInfo()
time.sleep(1)
m_click(100,120)#搜索到之後點擊
#win32api.keybd_event(13,0,0,0)#回車
#win32api.keybd_event(13,0,KEYEVENTF_KEYUP,0)
#win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
#win32gui.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)

def sendInfo():
time.sleep(1)
pasteInfo()
time.sleep(1)
win32api.keybd_event(18, 0, 0, 0) #Alt
win32api.keybd_event(83,0,0,0) #s
win32api.keybd_event(83,0,win32con.KEYEVENTF_KEYUP,0) #釋放按鍵
win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0)

def closeByUser(uname):
hwnd = win32gui.FindWindow('WeChatMainWndForPC', '微信')
win32api.keybd_event(18,0,0,0) #Alt
win32api.keybd_event(115,0,0,0) #F4
win32api.keybd_event(115,0,KEYEVENTF_KEYUP,0)
win32api.keybd_event(18,0,KEYEVENTF_KEYUP,0)

'''
searchByUser('Tony老師')
setText('Tony老師理發師')
sendInfo()
time.sleep(1)
searchByUser('文件傳輸助手')
setText('地表最強CPU')
sendInfo()
'''

def getNosuffixImgName(imgname):
return os.path.splitext(imgname)[0]

imgdir='imgs/'
imgs=os.listdir(imgdir)
for img in imgs:
searchByUser(getNosuffixImgName(img))
setImage(imgdir+img)
sendInfo()
time.sleep(1)
http://www.manongjc.com/detail/22-xfnkrxxytyxkisz.html

⑥ python,如何發送帶附件的郵件

可以通過以下代碼實現:

importsmtplib
fromemail.mime.textimportMIMEText
importemail.mime.multipart
fromemail.
fromemail.MIMEBaseimportMIMEBase
fromemailimportEncoders

defsend_mail():
mailto_list=['xxxx','xxx']#收件人
mail_host="xxxxx"#設置伺服器
mail_user="xxxx"#用戶名
mail_pass="xxxxxx"#口令
mail_postfix="xxxx.xxx"#發件箱的後綴
me="hello"+"<"+mail_user+"@"+mail_postfix+">"#這里的hello可以任意設置,收到信後,將按照設置顯示
content='Thisistestmail!'#郵件正文
msg=MIMEMultipart()
body=MIMEText(content,_subtype='html',_charset='gb2312')#創建一個實例,這里設置為html格式郵件
msg.attach(body)
msg['Subject']="SubjectTest"#設置主題
msg['From']=me
msg['To']=";".join(mailto_list)
#附件內容,若有多個附件,就添加多個part,如part1,part2,part3
part=MIMEBase('application','octet-stream')
#讀入文件內容並格式化,此處文件為當前目錄下,也可指定目錄例如:open(r'/tmp/123.txt','rb')
part.set_payload(open('test.txt','rb').read())
Encoders.encode_base64(part)
##設置附件頭
part.add_header('Content-Disposition','attachment;filename="test.txt"')
msg.attach(part)

try:
s=smtplib.SMTP()
s.connect(mail_host)#連接smtp伺服器
s.login(mail_user,mail_pass)#登陸伺服器
s.sendmail(me,mailto_list,msg.as_string())#發送郵件
s.close()
print'sendmailsucess'
returnTrue
exceptException,e:
printstr(e)
returnFalse

⑦ python通過get,post方式發送http請求和接收http響應


本文實例講述了python通過get,post方式發送http請求和接收http響應的方法。姿敏分享給輪敏大家供大家參考。
具體如下:
測試用CGI,名字為test.py,放在apache的cgi-bin目錄下:
#!/usr/bin/python
import cgi
def main():
print Content-type: text/htmln
form = cgi.FieldStorage()
if form.has_key(ServiceCode) and form[ServiceCode].value != :
print h1 Hello,form[ServiceCode].value,/h1
else:
print h1 Error! Please enter first name./h1
main()
python發送post和get請求
get請求:
使用get方式時,請求數據直接放在url中。
方法一、
?
7
8
import urllib
import urllib2
url =
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
?
7
import httplib
url =
conn = httplib.HTTPConnection(192.168.81.16)
conn.request(method=GET,url=url)
response = conn.getresponse()
res= response.read()
print res
post請求:臘冊枝
使用post方式時,數據放在data或者body中,不能放在url中,放在url中將被忽略。
方法一、
import urllib
import urllib2
test_data = {ServiceCode:aaaa,b:bbbbb}
test_data_urlencode = urllib.urlencode(test_data)
requrl =
req = urllib2.Request(url = requrl,data =test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
11
import urllib
import httplib
test_data = {ServiceCode:aaaa,b:bbbbb}
test_data_urlencode = urllib.urlencode(test_data)
requrl =
headerdata = {Host:192.168.81.16}
conn = httplib.HTTPConnection(192.168.81.16)
conn.request(method=POST,url=requrl,body=test_data_urlencode,headers = headerdata)
response = conn.getresponse()
res= response.read()
print res
對python中json的使用不清楚,所以臨時使用了urllib.urlencode(test_data)方法;
模塊urllib,urllib2,httplib的區別
httplib實現了http和https的客戶端協議,但是在python中,模塊urllib和urllib2對httplib進行了更上層的封裝。
介紹下例子中用到的函數:
1、HTTPConnection函數
httplib.HTTPConnection(host[,port[,stict[,timeout]]])
這個是構造函數,表示一次與伺服器之間的交互,即請求/響應
host 標識伺服器主機(伺服器IP或域名)
port 默認值是80
strict 模式是False,表示無法解析伺服器返回的狀態行時,是否拋出BadStatusLine異常
例如:
conn = httplib.HTTPConnection(192.168.81.16,80) 與伺服器建立鏈接。
2、HTTPConnection.request(method,url[,body[,header]])函數
這個是向伺服器發送請求
method 請求的方式,一般是post或者get,
例如:
method=POST或method=Get
url 請求的資源,請求的資源(頁面或者CGI,我們這里是CGI)
例如:
url=
或者
url=
body 需要提交到伺服器的數據,可以用json,也可以用上面的格式,json需要調用json模塊
headers 請求的http頭headerdata = {Host:192.168.81.16}
例如:
?
test_data = {ServiceCode:aaaa,b:bbbbb}
test_data_urlencode = urllib.urlencode(test_data)
requrl =
headerdata = {Host:192.168.81.16}
conn = httplib.HTTPConnection(192.168.81.16,80)
conn.request(method=POST,url=requrl,body=test_data_urlencode,headers = headerdata)
conn在使用完畢後,應該關閉,conn.close()
3、HTTPConnection.getresponse()函數
這個是獲取http響應,返回的對象是HTTPResponse的實例。
4、HTTPResponse介紹:
HTTPResponse的屬性如下:
read([amt]) 獲取響應消息體,amt表示從響應流中讀取指定位元組的數據,沒有指定時,將全部數據讀出;
getheader(name[,default]) 獲得響應的header,name是表示頭域名,在沒有頭域名的時候,default用來指定返回值
getheaders() 以列表的形式獲得header
例如:
?
1
2
3
4
5
date=response.getheader(date);
print date
resheader=
resheader=response.getheaders();
print resheader
列形式的響應頭部信息:
?
1
2
3
[(content-length, 295), (accept-ranges, bytes), (server, Apache), (last-modified, Sat, 31 Mar 2012 10:07:02 GMT), (connection, close), (etag, e8744-127-4bc871e4fdd80), (date, Mon, 03 Sep 2012 10:01:47 GMT), (content-type, text/html)]
date=response.getheader(date);
print date
取出響應頭部的date的值。
希望本文所述對大家的Python程序設計有所幫助。

熱點內容
python解壓zip 發布:2025-02-12 09:08:46 瀏覽:921
如何加強人員配置 發布:2025-02-12 09:07:54 瀏覽:417
lol一區為什麼伺服器好卡 發布:2025-02-12 09:02:22 瀏覽:629
安卓運營商cm是哪個版本 發布:2025-02-12 09:00:00 瀏覽:515
pythonmd5校驗 發布:2025-02-12 08:51:00 瀏覽:470
編程題解析 發布:2025-02-12 08:40:30 瀏覽:454
bilibi手機緩存目錄在 發布:2025-02-12 08:33:11 瀏覽:458
聽ti密碼是多少 發布:2025-02-12 08:22:15 瀏覽:289
淘寶上傳視頻憑證 發布:2025-02-12 08:06:46 瀏覽:879
java畫 發布:2025-02-12 08:01:00 瀏覽:550