使用以下代码我可以自动发送邮件,直到收到错误“UnicodeEncodeError:'ascii'编解码器无法对位置36-37中的字符进行编码:序数不在范围(128)中”。从那一刻起,我不断遇到同样的错误,并且找不到让它再次工作的方法。 “UnicodeEncodeError:'ascii'编解码器无法对位置 36 中的字符 '\xa0' 进行编码:序数不在范围 (128) 中”。我尝试将 EMAIL、receiver_mail 编码为 utf8,我在 csv 文件中读取/写入时设置了编码='utf-8' 我不知道我还能做什么
import smtplib
import ssl
import os
import csv
import fnmatch
import logging
import time
import shutil
logging.basicConfig(format='%(asctime)s %(message)s',level=logging.INFO)
from email import encoders
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header, decode_header
from email.utils import formataddr, encode_rfc2231
print("Send mails?")
premQuestion = input("Y/N:")
> get the date from folder name
if premQuestion.upper() == "Y":
rootdir = r'D:\Mailsunsent'
destdir = r'D:\Mailssent'
if len(os.listdir(rootdir)) == 0:
print("The selected folder is empty!\nVerify!")
else:
for file in os.listdir (rootdir):
d = os.path.join(rootdir, file)
target = os.path.join(destdir, file)
if os.path.isdir(d):
str(d)
fday = d.split()[-2:]
> create the csv file after another
with open('mailsload1.csv','r',newline='', encoding='utf-8') as csvin,
open('mailsload2.csv','w',newline='', encoding='utf-8') as csvout:
reader =csv.reader(csvin, delimiter=';')
writer =csv.writer(csvout, delimiter=';')
header = next(reader)
writer.writerow(header)
for name, nb, location, emailadress,senderMail,subject,passWord in reader:
writer.writerow([name,
nb,
f"D:\\Mailsunsent\\Mails to sent {' '.join(fday)}\\{name}",
emailadress,
senderMail,
subject,
passWord
])
with open('mailsload2.csv','r',newline='', encoding='utf-8') as csvin:
reader =csv.reader(csvin, delimiter=';')
header = next(reader)
data=[]
for row in reader:
dir_path = row[2]
count = len(fnmatch.filter(os.listdir(dir_path), '*.*'))
data.append(count)
linesNb = reader.line_num
with open('mailsload1.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file, delimiter=';')
rows = [row for row in reader]
i = 0
for row in rows:
for index, value in enumerate(row):
if value == '0':
row[index] = data[i]
i+=1
with open('mailsload2.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file,delimiter=';')
writer.writerows(rows)
countMails = 0
with open("mailsload2.csv", 'r', newline='', encoding='utf-8') as file:
reader = csv.reader(file, delimiter=';')
header = next(reader) # Skip header row
for row in reader:
if int(row[1]) > 0:
SMTP_SERVER = "some server mail"
PORT = 465
EMAIL = row[4]
PASSWORD = row[6]
subject = row[5]
html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Semnatura</title>
</head>
<body>
<br>
<br>
<pre style="font-style: Arial;"> With pleasure,</pre>
<p style="font-style: Arial;color: #00008B;"><b>Surname Name</b></p>
<p style="font-style: Arial;"><b>Some firm</b></p>
<p style="font-style: Arial;">Adress of firm</p>
<p style="font-style: Arial;"><span style="color: #00008B;">Phone:</span> some phone number <span style="color: #00008B;">Email: </span><a href="mailto:[email protected]">[email protected]</a></p>
</body>
</html>"""
bcc_email = row[4]
receiver_email = row[3]
message = MIMEMultipart()
message["From"]= Header(EMAIL, charset='utf-8', errors='strict')
message["To"]= Header(receiver_email, charset='utf-8', errors='strict')
message["Cc"]= Header(EMAIL, charset='utf-8', errors='strict')
message["Subject"]= Header(subject, charset='utf-8', errors='strict')
message.attach(MIMEText(html, "html", 'utf-8'))
dir_path = row[2]
files = fnmatch.filter(os.listdir(dir_path), '*.*')
for f in files: # add files to the message
file_path = os.path.join(dir_path, f)
with open(file_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=f)
message.attach(part)
attachment.close()
text = message.as_string()
context = ssl.create_default_context()
with smtplib.SMTP_SSL(SMTP_SERVER, PORT, context=context) as server:
server.login(EMAIL, PASSWORD)
server.sendmail(EMAIL,
[receiver_email,
bcc_email],
text
)
logging.info(f" Successfully sent email to {receiver_email}")
server.quit()
countMails += 1
time.sleep(20)
print(f'S-au trimis {countMails} mailuri din data de {' '.join(fday)}.')
shutil.move(d, target)
else:
quit()
```
整个消息是utf-8格式,但unicode错误出现在行:“server.sendmail(EMAIL, [receiver_email, bcc_email], text)”。