这是我的第一个py脚本,已经研究两天了,不知道具体是什么问题.One.py获取一个网页中的文章,然后保存到一个utf-8编码的文件中.Mail.py发送一个带有附件的邮件如果我分开执行两个脚本.先执行One.py脚本,生成一个附件文件,然后在控制台执行Mail.py传入One生成的附件文件路径,它能成功发送邮件.如果我在One.py中直接调用Mail.py中SendMail()方法传入附件发送邮件,就会报错:UnicodeEncodeError:'ascii'codeccan'tencodecharactersinposition1-9:ordinalnotinrange(128).One.py#-*-coding:utf-8-*-#scriptforpython3.2importurllib.request,re,sys,os.pathimportMail#获取网页内容defGetWebContent(url):returnurllib.request.urlopen(url).read().decode("utf-8")#获取网页中文章的内容defGetOntArticle():print(sys.getdefaultencoding())page=GetWebContent("http://www.wufazhuce.com")oneArticle=re.compile(r"one-articulo-titulo.*?",re.DOTALL).findall(page)oneArticleLink=re.compile(r'http.*?\"',re.I).findall(oneArticle[0])[0]oneArticleLink=oneArticleLink[0:(len(oneArticleLink)-1)]articleContent=GetWebContent(oneArticleLink)articleTitle=re.compile(r'articulo-titulo">.*?',re.DOTALL).findall(articleContent)[0]articleTitle=articleTitle[17:len(articleTitle[0])-6].expandtabs(0)#print(articleTitle)articleBody=re.compile(r'articulo-contenido">.*?',re.DOTALL).findall(articleContent)[0]articleBody=articleBody[20:len(articleBody)-6]#print(articleBody)articleFile=sys.path[0]+'\Article\Article.txt'#print(articleFile)#写入文件,稍后作为邮件的附件发送fileContent=open(articleFile,'w+',encoding="utf-8")fileContent.write(articleBody)fileContent.close()#Mail.SendMail(articleTitle,articleFile)if__name__=='__main__':GetOntArticle()Mail.py#-*-coding:utf-8-*-#scriptforpython3.2importos,sysimportsmtplibimportmimetypesfromemail.mime.multipartimportMIMEMultipartfromemail.mime.baseimportMIMEBasefromemail.mime.textimportMIMETextfromemail.mime.audioimportMIMEAudiofromemail.mime.imageimportMIMEImagefromemail.encodersimportencode_base64#邮件帐号和密码MAIL_QQ_USER="xxxx@qq.com"MAIL_QQ_PWD="xxxx"MAIL_QQ_HOST="smtp.qq.com"#接受方邮件帐号RECIPIENT=["xxxx@qq.com"]print(sys.getdefaultencoding())classQMail():#初始化def__init__(self,user,pwd,host):self.mail_user=userself.mail_pwd=pwdself.mail_server=smtplib.SMTP()self.mail_server.connect(host)self.mail_server.ehlo()self.mail_server.login(self.mail_user,self.mail_pwd)def__del__(self):self.mail_server.close()#发送邮件defsend_mail(self,recipient,subject,text,file_path):msg=MIMEMultipart()msg["From"]=self.mail_usermsg["Subject"]=subjectmsg["To"]=",".join(recipient)msg.attach(MIMEText(text))msg.attach(self.get_attachment(file_path))self.mail_server.sendmail(self.mail_user,recipient,msg.as_string())print("mailsend")#添加邮件附件defget_attachment(self,file_path):file_name=file_path.split("\\")[-1]attachment=MIMEText(open(file_path,'rb').read(),'base64','utf-8')attachment["Content-Type"]='application/octet-stream'attachment["Content-Disposition"]='attachment;filename='+file_nameprint("read")returnattachmentdefSendMail(articleTitle,articleFile):mail=QMail(MAIL_QQ_USER,MAIL_QQ_PWD,MAIL_QQ_HOST)mail.send_mail(RECIPIENT,articleTitle,'pythonSendToKindle',articleFile)if__name__=='__main__':SendMail("sendtextmail",r"d:\PythonProjects\SendToKindle\Article\Article.txt")
添加回答
举报
0/150
提交
取消