python将mailBody附加到电子邮件中不起作用

时间:2018-09-17 14:15:51

标签: python subprocess

我有一个下面的脚本,该脚本对于rsync正常工作,该脚本实际上将文件从远程主机拉到服务器,并从其运行在dest文件夹下。

但是rsync可以正常工作,但是基本上msg = 'message + "rsync process completed"'的邮件部分并未作为电子邮件发送。

我不知道自己在做什么错!

import os
import sys
import subprocess
import argparse
import smtplib

#Dir Structure
dst = "/infralogs/external_dns_logs"
rsync_user = "root"
mailFrom = 'robo@helisis.com'
mailTo = 'robo@helisis.com'
mailSub = 'Rsync status'
msg = ""

parser = argparse.ArgumentParser()
parser.add_argument("-n","--hosts",dest="hosts",help="enter remote host/hosts name, comma seperated",metavar="HOSTS")
parser.add_argument("-s","--src",dest="source",help="source file/directory",metavar="SOURCE")
parser.add_argument("-e","--exclude",dest="exclude",help="Exclude files/Directories, comma seperated list",metavar="EXCLUDE")

if len(sys.argv) < 7:
    print(len(sys.argv))
    parser.print_help()
    parser.exit()

args = parser.parse_args()

def sync(host,dst):
    exclude = ""
    if not os.path.exists(dst):
        os.mkdir(dst)
    if ',' in args.exclude:
        for excl in args.exclude.split(','):
            exclude = exclude + " --exclude " + excl
        cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz %s %s@%s:%s %s/"%(exclude,rsync_user,host,args.source,dst)
    else:
        cmd = "rsync -e 'ssh -o StrictHostKeyChecking=no' -auPz --exclude %s %s@%s:%s %s/"%(args.exclude,rsync_user,host,args.source,dst)
    print(cmd)
    message = cmd
    p = subprocess.Popen(cmd,shell=True)
    p.wait()
    print("DONE")
    msg = message + "rsync process completed"

mailBody = "From: %s\nTo: %s\nSubject: %s\n\n%s" %(mailFrom,mailTo,mailSub,msg)

if ',' in args.hosts:
    for host in args.hosts.split(','):
        dest = dst + "/" + host
        sync(host,dest)
else:
    dest = dst + "/" + args.hosts
    sync(args.hosts,dest)

try:
    Mail = smtplib.SMTP('mailserver.global.helisis.com', 25, 'localhost.helisis.com')
    Mail.sendmail(mailFrom,mailTo,mailBody,msg)
    print("Mail Sent to %s" %(mailTo))
except:
    print("Mail Failed")

从上面的脚本在终端上输出结果:

$ ./log_rsync -n remote_Server -s /var/log/infoSec/ -e "null"

bind.log
           0 100%    0.00kB/s    0:00:00 (xfer#1, to-check=7/9)
default.log
       12769 100%   12.18MB/s    0:00:00 (xfer#2, to-check=6/9)
general.log
        9553 100%    4.56MB/s    0:00:00 (xfer#3, to-check=5/9)
lame-servers.log
         663 100%  129.49kB/s    0:00:00 (xfer#4, to-check=4/9)
network.log
           0 100%    0.00kB/s    0:00:00 (xfer#5, to-check=3/9)
notify.log
        3286 100%  356.55kB/s    0:00:00 (xfer#6, to-check=2/9)
queries.log
         578 100%   47.04kB/s    0:00:00 (xfer#7, to-check=1/9)
query-errors.log
           0 100%    0.00kB/s    0:00:00 (xfer#8, to-check=0/9)

sent 176 bytes  received 4303 bytes  814.36 bytes/sec
total size is 26849  speedup is 5.99
DONE
Mail Sent to robo@helisis.com

邮件服务工作正常,但是包含消息msg的{​​{1}}变量未得到发送带有主题的剩余电子邮件,该问题正在起作用,问题似乎与msg = message + "rsync process completed"部分有关没有被正确调用或打开。

只是一种替代方法!

虽然我采用下面的方法,但其中包含了msg地址,To和消息Subject,它们可以正常工作并发送电子邮件,但真正的问题仍然是相同的如果我想在此加入Rsync Process Completed Successfully.或说要在此公开msg部分,那怎么办!

msg

3 个答案:

答案 0 :(得分:1)

能否请您尝试使用MIMEMultipart发送消息。我应该这样工作。

import smtplib
from email.mime.multipart import MIMEMultipart

EmailSender = "robo@localhost.helisis.com"
EmailReceiver = "robo@helisis.com"

msgBody = '''From: dnsmailer <netrobo@helisis.com>
To: To Person <robo@helisis.com>
Subject: rsync Status from  infra-syslog

Rsync Process Completed Succesfully.
'''

try:
    Mail = smtplib.SMTP('mailserver.global.helisis.com', 25, 'localhost.helisis.com')
    mail_obj = MIMEMultipart()
    mail_obj["From"] = EmailSender
    mail_obj["To"] = EmailReceiver
    mail_obj["Subject"] = "rsync Status from  infra-syslog."
    mail_obj.preamble = "rsync Status from  infra-syslog. "
    msgBody = "Rsync Process Completed Successfully!"  # Message body
    mail_obj.attach(MIMEText(message, 'plain'))
    Mail.sendmail(from_addr=[EmailSender], to_addrs=[EmailReceiver], msg=mail_obj.as_string())
    print("Mail Sent to %s" % (EmailReceiver))
except Exception as error:
    print("Mail Failed - {}".format(error))

答案 1 :(得分:1)

问题在于string value; decimal number; NumberStyles style; CultureInfo provider; value = "$1,633.75"; style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; provider = new CultureInfo("en-US"); number = Decimal.Parse(value, style, provider); Console.WriteLine("'{0}' converted to {1}.", value, number); 是在msg函数内部计算的(可以循环调用),然后被遗忘了(意味着没有存储)。

因此,当您想在邮件正文中使用它时,它将不再可用。您必须在可用时使用它并直接调整邮件正文,或者更好地将其存储在列表中,然后使用它来构建邮件正文。该代码可能变为:

sync

答案 2 :(得分:0)

只要随便放一点对我有用的电子邮件,就象smtplib一样,抛出一些我较早应用的错误,下面是有效的电子邮件部分,可能有人会在找一样的东西:-) < / p>

非常感谢@Serge和@Vijay对此提供帮助。

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib


email_sender = "syslogger@helisis.com"
email_receiver = "robo@helisis.com, robo01@helisis.com, robo02@helisis.com"


try:
    Mail = smtplib.SMTP('mailserver.global.helisis.com', 25, 'localhost.helisis.com')
    mail_obj = MIMEMultipart('alternative')
    mail_obj["From"] = email_sender
    mail_obj["To"] = email_receiver
    mail_obj["Cc"] = "someone@helisis.com"
    mail_obj["Subject"] = "rsync Status from  infra-syslog."
    mail_obj.preamble = "rsync Status from  infra-syslog. "
    msgBody = "Rsync Process Completed Successfully!"  # Message body
    mail_obj.attach(MIMEText(msg, 'plain'))
    Mail.sendmail(from_addr=[email_sender], to_addrs=[email_receiver],msg=mail_obj.as_string())
    print("Mail Sent to %s" % (email_sender))
except Exception as error:
    print("Mail Failed - {}".format(error))