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()