我是python的新手,有一个任务是发送多个带有相关附件的电子邮件。我将详细说明,一个文件夹包含多个pdf文件,每个文件包含一些文本,包括电子邮件ID。我需要从每个pdf文件中读取电子邮件ID,并将相同的文件作为附件发送到pdf文件中的mailid。以下是供参考的代码
# Get the count of files in the folder
import os
import re
global str
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
cpt = sum([len(files) for r, d, files in
os.walk("D:\MyOfficeDocuments\ADCB\PythonScripts\PdfFiles")])
#Reading Mail from each pdf file and send the same file as attachment to
these mails
import PyPDF2
from os import listdir
from os.path import isfile, join
from PyPDF2 import PdfFileWriter, PdfFileReader
mypath='D:\MyOfficeDocuments\ADCB\PythonScripts\PdfFiles'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in onlyfiles:
count = 1
while count <cpt:
os.chdir(r'D:\MyOfficeDocuments\ADCB\PythonScripts\PdfFiles')
pdfFileObj = open(file,'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
count +=1
text = pageObj.extractText()
email_user='[email protected]'
eline = re.findall('\S+@\S+.com', text)
email_send=eline
print(file)
password='harshi54537'
subject='Python !'
msg=MIMEMultipart()
msg['From']=email_user
msg['To']=', '.join(email_send)
#listalink = " ".join(listalink)
msg['Subject']=subject
#print (email_send)
body='Hi there, sending this email from python using python scripting'
msg.attach(MIMEText(body,'plain'))
filename
='D:\MyOfficeDocuments\ADCB\PythonScripts\Destination\Document.txt'
attachment=open(file,'rb')
#print(attachment)
part=MIMEBase('application','pdf')
part.set_payload(attachment.read())
part.add_header('Content-Disposition',"attachement; filename="+file)
msg.attach(part)
#email.encoders.encode_base64(part)
print('x')
text=msg.as_string()
#text=msg.encode("utf8")
#text=msg.as_string().encode('utf-8','ignore')
#text=msg.as_string().encode('ascii','ignore')
server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,password)
server.sendmail(email_user,email_send,text)
#server.sendmail(email_user,email_send,msg.encode("utf8"))
server.quit()
根据上面的代码,我收到如下所示的错误消息
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError:'ascii'编解码器无法对位置559-562中的字符进行编码:序数不在范围内(128)
但是,如果我更改下面的代码
text=ms.as_string().encode("UTF")
我没有收到任何错误,但附件显示为空白
请告诉我确切问题的位置以及获取空白pdf附件的问题。
我请求您是否有任何代码建议,请仅建议pdf文件
先谢谢Madhu
您的问题是您使用简单的MIMEBase
作为(二进制)pdf文件。由于MIMEBase
是各种可能的消息类型的父类,因此它不对其有效负载进行编码,并且您的消息包含原始的8位字节。
这里有两个可能的修复:
...
from email.encoders import encode_base64
...
part=MIMEBase('application','pdf')
part.set_payload(attachment.read())
part.add_header('Content-Disposition',"attachement; filename="+file)
encode_base64(part)
msg.attach(part)
...
MIMEApplication
默认编码所有内容:
...
from email.mime.application import MIMEApplication
...
part=MIMEApplication(attachment.read(),'pdf')
part.add_header('Content-Disposition',"attachement; filename="+file)
msg.attach(part)
...
我建议你使用第二种方式,因为MIMEBase
的文档说:
通常你不会创建特定于MIMEBase的实例,尽管你可以。 MIMEBase主要作为更具体的MIME感知子类的方便基类提供。