我正在尝试制作一个python脚本来验证一些文件,如果有一些更改,则发送电子邮件。在
剧本写得不错,但如果我写了一些特别的字符,他就不会发邮件了。。。在
我已经找过网站编码,但我不能解决我的问题。在
这是我的剧本:
#!/usr/bin/env python3
# -*- coding:Latin-1 -*-
import os
import shutil
import smtplib
# Fonctions
def compare (old,new):
x = 0
if old == new:
print('Les fichiers sont à jour')
x = 0
if old != new:
print('Nouveaux Fichiers de tests')
x = 1
mail = open('mail.txt', 'w', encoding='utf8')
mail.write("test d'écriture\n")
mail.write("si ca marche c'est top\n")
mail.close()
return x
# Récupération des fichiers
os.chdir("/var/www/corealpi/integration/integration_core")
rep = os.getcwd()
print(rep)
# copie du fichier tests.txt
shutil.copyfile('tests.txt','/home/git/integration/tests.new')
os.chdir("/home/git/integration")
rep_int = os.getcwd()
print(rep_int)
# Ouverture des fichiers
oldFile = open('tests.old','r')
newFile = open('tests.new','r')
tOld = oldFile.read()
tNew = newFile.read()
verif = compare (tOld,tNew)
print(verif)
# Envoie de mails
if verif == 1:
from email.mime.text import MIMEText
mailfile = 'mail.txt'
with open(mailfile) as fp:
# Create a text/plain message
msg = MIMEText(fp.read())
msg.set_charset('utf-8')
msg['Subject'] = 'Nouveaux Fichiers de %s' % mailfile
msg['From'] = 'sender@mail.fr'
msg['To'] = 'receiver@mail.fr'
# Envoi du message
s = smtplib.SMTP('192.168.3.2')
s.send_message(msg)
s.quit
else:
print('Rien à signaler')
我用utf8编码。。。但它似乎不适用于send_message
?但也许我把我弄糊涂了,或者我的生活太复杂了。在
有人能帮我吗?在
编辑:我尝试过多种编码方式,但我解决不了这个问题。。。请注意:)
谢谢你的帮助。在
你忘了说什么是你的平台上的默认编码,如果你使用的是Python2或3。在
我假设您使用的是Python2,但是对于Python3来说应该没有什么不同。在
实际上,您应该在
email.mime.text.MIMEText
对象中设置字符集,因为doc说字符集默认为usascii,这在这里是错误的。您应该使用:其中charset是在其中编码数据的字符集(如果您使用Python2),或者您要在其中编码邮件的字符集是使用python3。在
如果要以UTF8独立于Python 2中的本地编码发送邮件,请首先将其解码为unicode字符串,然后应用输出字符集:
^{pr2}$相关问题 更多 >
编程相关推荐