python郵件發送
⑴ 如何通過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發送email
有好幾個模塊,可以實現.
這里用smtplib和email來實現了一個簡單的不帶附件的郵件發送
以163郵件為服務郵箱配置的。
#coding:utf-8
importsmtplib
fromemail.mime.textimportMIMEText
fromemail.mime.multipartimportMIMEMultipart
importsys
reload(sys)
sys.setdefaultencoding("utf8")
#配置收發件人,可以發送給多個
recvaddress=['[email protected]','[email protected]']
#163的用戶名和密碼,修改為你自己的
sendaddr_name='[email protected]'
sendaddr_pswd='your_password'
classSendMail:
def__init__(self,recver=None):
"""接收郵件的人:listortuple"""
ifrecverisNone:
self.sendTo=recvaddress
else:
self.sendTo=recver
defsend(self,sub,content):
"""發送郵件"""
self.msg=MIMEMultipart()
#設置發送郵件
self.msg['from']=sendaddr_name
try:
#設置郵箱伺服器
smtp=smtplib.SMTP('smtp.163.com',25)
#登錄
smtp.login(sendaddr_name,sendaddr_pswd)
#設置發送主題
self.msg['Subject']=sub
#設置郵件內容
self.msg.attach(MIMEText(content))
#發送郵件
smtp.sendmail(self.msg['from'],self.sendTo,self.msg.as_string())
smtp.close()
print(u"發送郵件成功")
exceptException,e:
print(u'發送郵件失敗:'+str(e))
raise
#調用
s=SendMail()
subject="主題"
content="這里是郵件內容"
s.send(subject,content)
⑶ python smtp郵件發送失敗怎麼辦
以下代碼調試通過:
#coding:utf-8
importsmtplib
fromemail.mime.textimportMIMEText
fromemail.headerimportHeader
sender='[email protected]'
receiver='[email protected]'
subject='pythonemailtest'
smtpserver='smtp.139.com'
username='[email protected]'
password='xxxxxx'
msg=MIMEText('你好','text','utf-8')#中文需參數『utf-8',單位元組字元不需要
msg['Subject']=Header(subject,'utf-8')
smtp=smtplib.SMTP()
smtp.connect('smtp.139.com')
smtp.login(username,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
運行效果:
⑷ 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發送帶的郵件
.headerimportHeaderfromemail.mime.textimportMIMETextfromemail.utilsimportparseaddr,formataddrdefsend_email(from_addr,to_addr,subject,password):
msg=MIMEText("郵件正文",'html','utf-8')
msg['From']=u'<%s>'%from_addr
msg['To']=u'<%s>'%to_addr
msg['Subject']=subject
smtp=smtplib.SMTP_SSL('smtp.163.com',465)
smtp.set_debuglevel(1)
smtp.ehlo("smtp.163.com")
smtp.login(from_addr,password)
smtp.sendmail(from_addr,[to_addr],msg.as_string())if__name__=="__main__":
#這里的密碼是開啟smtp服務時輸入的客戶端登錄授權碼,並不是郵箱密碼
#現在很多郵箱都需要先開啟smtp才能這樣發送郵件
send_email(u"from_addr",u"to_addr",u"主題",u"password")
⑹ 如何在python程序中發郵件
比如我用自己的 139 郵箱 [email protected]
發送郵件到網易郵箱 也是我的辦公郵箱 [email protected]
以下代碼調試通過:
#coding:utf-8
importsmtplib
fromemail.mime.textimportMIMEText
fromemail.headerimportHeader
sender='[email protected]'
receiver='[email protected]'
subject='pythonemailtest'
smtpserver='smtp.139.com'
username='[email protected]'
password='xxxxxxxx'
msg=MIMEText('你好lucia這是你的第一封python發出的郵件','text','utf-8')
#中文需參數『utf-8',單位元組字元不需要
msg['Subject']=Header(subject,'utf-8')
smtp=smtplib.SMTP()
smtp.connect('smtp.139.com')
smtp.login(username,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
運行結果:
⑺ 如何使用python發送各類郵件
以下代碼調試通過:
#coding:utf-8
importsmtplib
fromemail.mime.textimportMIMEText
fromemail.headerimportHeader
sender='[email protected]'
receiver='[email protected]'
subject='pythonemailtest'
smtpserver='smtp.139.com'
username='[email protected]'
password='xxxxxxxx'
msg=MIMEText('你好lucia這是你的第一封python發出的郵件','text','utf-8')
#中文需參數『utf-8',單位元組字元不需要
msg['Subject']=Header(subject,'utf-8')
smtp=smtplib.SMTP()
smtp.connect('smtp.139.com')
smtp.login(username,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
運行效果:
⑻ 如何用python自動發送郵件
注意如果使用qq的smtp轉發功能的話,需要在設置頁面中將該功能打開,然後設定密碼,改密碼就是賦值給下文password中的。
開啟smtp轉發功能文檔
[python]view plain
#fromemail.MIMETextimportMIMEText#
fromemail.MIMETextimportMIMEText
fromemail.HeaderimportHeader
msg=MIMEText('hello,sendbypython','plain','utf-8');
from_addr="*****@qq.com"#
password="******"#password
to_addr="****@qq.com"#targetemailaddress
smtp_server="smtp.qq.com"#smtpseverdomainforqqissmtp.qq.com
importsmtplib
server=smtplib.SMTP(smtp_server,25);
server.set_debuglevel(1)
server.login(from_addr,password);
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
上面這個是沒有主題的,有主題的話建議採用下面這個代碼
下面是連續發送有主題的文件10封
[python]view plain
fromemail.HeaderimportHeader
fromemail.MIMETextimportMIMEText
fromemailimportencoders
fromemail.utilsimportparseaddr,formataddr
importsmtplib
def_format_addr(s):
name,addr=parseaddr(s)
returnformataddr((Header(name,'utf-8').encode(),addr))
from_addr="*****@qq.com"#
password="******"#password
to_addr="****@qq.com"#targetemailaddress
smtp_server="smtp.qq.com"#smtpseverdomainforqqissmtp.qq.com
fornuminrange(1,11):
msg=MIMEText('hello,sendbyTom','plain','utf-8');
msg['From']=_format_addr('Tom<%s>'%from_addr)
msg['To']=_format_addr('addministrator<%s>'%to_addr)
msg['Subject']=Header('ThegreetingfromTom','utf-8').encode()
server=smtplib.SMTP(smtp_server,25)
server.set_debuglevel(1)
server.login(from_addr,password)
#server.sendmail(from_addr,[to_addr],msg.as_string())
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
⑼ python 怎麼生出成一個表格,並發送郵件
# -*- coding: utf-8 -*-
#程序名稱:自動化缺陷報告腳本
#程序描述:實現從本地路徑讀取excel文件內容,並繪制HTML表格,將內容寫入郵件正文區發送
#編寫時間:2014.11.29-2014.12.4
#作者:劉琳澤
#解釋環境:Windows 7家庭高級版 Python 2.7.8IDLE
#引入excel文檔相關庫
import xlrd
import os,time
#引入郵件相關庫
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import base64
#處理從excel中讀取的float類型數據的類
#目前集成兩種處理:(1)float到int型的轉換(2)float到str型的轉換,後續有需要可以增加方法以集成其他類型的轉換
class judgeFloat:
def floatToInt(self,variable):
variable="%d"%variable
return variable
def floatToStr(self,variable):
variable=xlrd.xldate_as_tuple(variable,0)
variable=list(variable)
if variable[1]<10:
variable[1]='0'+str(variable[1])
variable=str(variable[0])+str(variable[1])+str(variable[2])
return variable
#確定文檔是否修改的函數:獲取文檔的修改時間與本地時間對比,不一致要求用戶確認是否繼續執行,一致則直接執行
def openFile(filename,address):
filetime=time.strftime("%Y/%m/%d",time.localtime(os.stat(address+filename).st_mtime))
local=time.strftime("%Y/%m/%d",time.localtime())
if filetime!=local:
single=input("文檔今天還沒有修改過,請確認是否繼續?確認請輸入1後點擊回車,否則輸入2點擊回車。")
if single==1:
pass
elif single==2:
exit()
else:
print '您的輸入有誤!腳本即將結束。'
time.sleep(5)
exit()
else:
pass
#寫郵件的函數
def mailWrite(filename,address):
header='<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>'
th='<body text="#000000">committed缺陷詳情:<table border="1" cellspacing="0" cellpadding="3" bordercolor="#000000" width="1800" align="left" ><tr bgcolor="#F79646" align="left" ><th>標識</th><th>摘要</th><th>狀態</th><th>優先順序</th><th>嚴重性</th><th>標記</th><th>所有者</th><th>創建時間</th><th>修改時間</th></tr>'
#打開文件
filepath=address+filename
book=xlrd.open_workbook(filepath)
sheet=book.sheet_by_index(0)
#獲取行列的數目,並以此為范圍遍歷獲取單元數據
nrows = sheet.nrows-1
ncols = sheet.ncols
body=''
cellData=1
for i in range(1,nrows+1):
td=''
for j in range(ncols):
#讀取單元格數據,賦給cellData變數供寫入HTML表格中
cellData=sheet.cell_value(i,j)
#調用浮點型轉換方法解決讀取的日期內容為浮點型數據的問題
if isinstance(cellData,float):
if j==0 and i>0:
cellDataNew=judgeFloat()
cellData=cellDataNew.floatToInt(cellData)
else:
cellDataNew=judgeFloat()
cellData=cellDataNew.floatToStr(cellData)
else:
pass
tip='<td>'+cellData+'</td>'
#並入tr標簽
td=td+tip
tr='<tr>'+td+'</tr>'
#為解決字元串拼接問題增設語句,tr從excel中讀取出來是unicode編碼,轉換成UTF-8編碼即可拼接
tr=tr.encode('utf-8')
#並入body標簽
body=body+tr
tail='</table></body></html>'
#將內容拼接成完整的HTML文檔
mail=header+th+body+tail
return mail
#發送郵件
def mailSend(mail):
#設置發件人
sender = '***'
#設置接收人
receiver = '***@***.com'
#設置郵件主題
subject = '測試郵件,請忽略!'
#設置發件伺服器,即smtp伺服器
smtpserver = 'smtp.***.net'
#設置登陸名稱
username = '***@***.net'
#設置登陸密碼
password = '******'
#實例化寫郵件到正文區,郵件正文區需要以HTML文檔形式寫入
msg = MIMEText(mail,'html','utf-8')
#輸入主題
msg['Subject'] = subject
#調用郵件發送方法,需配合導入郵件相關模塊
smtp = smtplib.SMTP()
#設置連接發件伺服器
smtp.connect('smtp.***.net')
#輸入用戶名,密碼,登陸伺服器
smtp.login(username, password)
#發送郵件
smtp.sendmail(sender, receiver, msg.as_string())
#退出登陸並關閉與發件伺服器的連接
smtp.quit()
#入口函數,配置文件地址和文件名
def main():
filename='Sheet1.xlsx'
address='d:/defectManage/'
openFile(filename,address)
mail=mailWrite(filename,address)
mailSend(mail)
#調用執行main函數
if __name__=="__main__":
main()
⑽ python 發送郵件
以下腳本測試通過!!!!!
fromTkinterimportTk
fromtimeimportsleep
importwin32com.clientaswin32
warn=lambdaapp:showwarning(app,"Exit?")
Range=range(3,8)
defoutlook():
app="Outlook"
olook=win32.gencache.EnsureDispatch("%s.Application"%app)
mail=olook.CreateItem(win32.constants.olMailItem)
recip=mail.Recipients.Add("[email protected]")
subj=mail.Subject="Python-to-%sDemo"%app
body=["Line%d"%iforiinRange]
body.insert(0,"%s "%subj)
body.append(" Th-th-th-that'sallfolks!")
mail.Body=" ".join(body)
mail.Send()
'''
ns=olook.GetNamespace("MAPI")
obox=ns.GetDefaultFolder(win32.constants.olFolderOutbox)
obox.Display()
obox.Items.Item(1).Display()
'''
warn(app)
olook.Quit()
if__name__=="__main__":
Tk().withdraw()
outlook()