简体   繁体   English

Python:通过crontab发送电子邮件时文件附件不起作用

[英]Python: file attachment not working while sending email by crontab

The following source code is working fine when running manually but with crontab job mail is successfully sending but files are not attached.How can I fix it? 手动运行时,以下源代码可以正常运行,但可以成功发送crontab作业邮件但未附加文件,如何解决?

#!/usr/bin/python

import smtplib
import os
import datetime
import glob
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

now = datetime.datetime.now()
fi = now.strftime("%d%m%Y" '_0600_final.txt')
files1=glob.glob('*%s'%fi)
time.sleep(20)
print(files1)
me = 'abc@abc.com'
you = ['abc@abc.com']  
msg = MIMEMultipart('alternative')
msg['Subject'] = "abc Report"
msg['From'] = me
msg['To'] = ", ".join(you)
text = "Hi!\n\nPlease find attached today's Counter files.\n\nRegards,\nabc"
part1 = MIMEText(text, 'plain')
msg.attach(part1)

for f in files1:  
    file_path = os.path.join('/tmp/', f)
    print(file_path)
    attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
    attachment.add_header('Content-Disposition','attachment', filename=f)
    msg.attach(attachment)
s = smtplib.SMTP('10.0.0.1')
s.sendmail(me, you, msg.as_string())
s.quit()

Here is crontab job entry: 这是crontab作业条目:

0 9 * * * python /tmp/send_mail_2.py

I think this issue is related to the folder where the attachment are located. 我认为此问题与附件所在的文件夹有关。

Keep in mind that if you run your script from crontab your python execution will probably be in a different folder than the one you're executing it manually from. 请记住,如果您从crontab运行脚本,则python执行可能与您从中手动执行脚本的位置不同。

Therefore I suggest two possible solutions: 因此,我建议两种可能的解决方案:

  • Use absolute paths for your attachments 为附件使用绝对路径
  • Move Python path into your script path as soon as the script starts 脚本启动后立即将Python路径移至脚本路径

You can achieve the 2nd result with a similar snippet: 您可以使用类似的代码段获得第二个结果:

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

If you want to troubleshoot and better understand what is going on you could simply run the current version of your script using crontab and save its current working directory in a file using something similar: 如果您想进行故障排除并更好地了解正在发生的情况,则可以使用crontab来运行脚​​本的当前版本,然后使用类似的方法将其当前工作目录保存在文件中:

with open('somefile.txt', 'a') as the_file:
    the_file.write(os.getcwd())

Edit: The issue was solved using the 2nd option suggested: Move Python path into your script path as soon your script starts . 编辑:使用建议的第二个选项解决了该问题: 脚本启动后立即将Python路径移到脚本路径中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM