运行sendgrid脚本可以手动运行,但是在crontab下运行时会失败

时间:2019-11-18 08:10:14

标签: python ubuntu cron sendgrid

我的目标是每周使用sendgrid python软件包将通过R脚本创建的pdf文件发送给多个涉众。手动运行R脚本和python邮件脚本时,邮件和附件将成功发送。但是当我在cron作业下运行它们时,邮件无法发送

创建的pdf文件为test.pdf

R脚本的位置是

/home/username/script.R

Python脚本的位置是

/home/username/run.py

run.py的内容如下

import base64
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (
  Mail, Attachment, FileContent, FileName,
  FileType, Disposition, ContentId)
from sendgrid.helpers.mail import Mail

message = Mail(
  from_email='from_email@gmail.com',
  to_emails=['to_email1@gmail.com','to_email_2@gmail.com','to_email_3@gmail.com','to_email_4@gmail.com'],
  subject='Mail',
  html_content='<strong>Please find attached</strong>')
file_path = 'test.pdf'
with open(file_path, 'rb') as f:
  data = f.read()
f.close()
encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('application/pdf')
attachment.file_name = FileName('test_filename.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Example Content ID')
message.attachment = attachment
try:
  sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
  response = sendgrid_client.send(message)
  print(response.status_code)
  print(response.body)
  print(response.headers)
except Exception as e:
  print(e.message)

在crontab中,我已经通过以下方式运行R和Python文件

0 8 * * 1  Rscript /home/username/script.R
10 8 * * 1 python /home/username/run.py


使用grep CRON /var/log/syslog查看cron日志后,我看到以下消息

CRON[27260]: (username) MAIL (mailed 1 byte of output but got status 0x0001 from MTA#012)

Python脚本在手动条件下运行良好,但在cron上自动运行时失败。我已经按照sendgrid python软件包进行了必备的API身份验证。是否有关于crontab我错过的重要设置? 操作系统如下

Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:        18.04
Codename:       bionic

谢谢!

0 个答案:

没有答案