我想使用 python、django 和 crontab 发送自动邮件。所以我做了以下事情。
创建了一个 cron_tab.py(位于文件夹 home/myhome/django/myapp/registration/cron_tab.py 中),如下所示:
from django.core.mail import send_mail, EmailMessage,EmailMultiAlternatives
subject, from_email, to = 'hello', 'testmailing@gmail.com', 'robert@gmail.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
然后使用终端,我通过发出以下命令进入 crontab
crontab -e
我安排的任务是这样的
* 1 * * * /home/myhome/django/myapp/registration/cron_tab.py
但是我没有收到邮件。我究竟做错了什么?请有人帮助我。更改文件模式后,出现以下错误并粘贴回溯
myhome@myhome:~/django/myapp/registration$ ./cron_tab.py
from: can't read /var/mail/django.core.mail
./cron_tab.py: line 3: subject: command not found
./cron_tab.py: line 4: from_email: command not found
./cron_tab.py: line 5: to: command not found
./cron_tab.py: line 6: text_content: command not found
./cron_tab.py: line 7: html_content: command not found
./cron_tab.py: line 8: syntax error near unexpected token `('
./cron_tab.py: line 8: `msg = EmailMultiAlternatives(subject, text_content, from_email,
[to])'
最佳答案
我认为您的cron_tab.py
没有从setting.py
读取django 配置。然后从 shell 运行这个脚本会发生什么?
无论如何你应该考虑使用custom management command为了这个任务。
关于python - 如何使用 python 和 crontab 安排工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27887393/