Linux daemonからGmailを送信したい
Pythonで書いたGmail送信をdeamonから実行したい。
プロンプトから実行して、Gmail送信できることは確認できました。
このPythonスクリプトをサービスに登録して、daemonから動かすと、送信されません。
デバックの方法、送信されない理由を調べる方法等があれば教えてほしいです。
#ソース
import string
import time
import os
import sys
import datetime
import dateutil
from dateutil.relativedelta import relativedelta
import boto3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formatdate
accesskey = "xxxxxxxxxxxxxxxxxxxx"
secretkey = "xxxxxxxxxxxxxxxxxxxx"
region = "ap-northeast-1"
def sendShortMessage(title,msg):
print("send to iPhone")
boto3.set_stream_logger()
try:
#print("client")
sns = boto3.client("sns", aws_access_key_id=accesskey, aws_secret_access_key=secretkey, region_name=region)
#print("publish")
response = sns.publish(PhoneNumber = "+81xxxxxxxxxxxx",Subject = title,Message = msg)
#print("response")
except Exception as err:
print(err.code)
def sendMsg_eMail(from_address, to_address, cc_address, subject, body, encode):
gmail_pass="app-passwd"
SMTP="smtp.gmail.com"
PORT=587
msg=MIMEText(body,"plain",encode)
msg["From"]=from_address
msg["To"]=to_address
msg["Subject"]=Header(subject, encode)
try:
print("mail Sending now...")
send = smtplib.SMTP(SMTP,PORT)
# send.set_debuglevel(True)
send.ehlo()
send.starttls()
send.ehlo()
send.login(from_address,gmail_pass)
send.send_message(msg)
send.close()
except Exception as e:
print("except: "+str(e))
else:
print("{0} send message.".format(to_address))
def start_mail_send():
date_start = datetime.date.today()
mail_to="xxxxxxxxx@yahoo.co.jp"
mail_from="yyyyyyyyyyy@gmail.com"
mail_cc="zzzzzzzzzz@i.softbank.jp"
mail_subject="test report start"
mail_body="service start " + date_start.strftime('%Y/%m/%d')
mail_encode="utf-8"
sendMsg_eMail(mail_from, mail_to, mail_cc, mail_subject, mail_body, mail_encode)
def main_unit():#10秒おきに時刻を書き込む
#print("test start")
start_mail_send()
counter = 2
while counter > 0:
filepath = '/home/orca/test.log'
log_file = open(filepath,'a')
try:
log_file.write(time.ctime()+"\n")
finally:
log_file.close()
time.sleep(10)
print("test end.")
def daemonize():
pid = os.fork()#ここでプロセスをforkする
if pid > 0:#親プロセスの場合(pidは子プロセスのプロセスID)
pid_file = open('/home/orca/python_daemon.pid','w')
pid_file.write(str(pid)+"\n")
pid_file.close()
sys.exit()
if pid == 0:#子プロセスの場合
main_unit()
if __name__ == "__main__":
while True:
daemonize()
#サービス登録
#/usr/lib/systemd/system/mail_send.service
[Unit]
Description=mail send
[Service]
Type=simple
Restart=on-failure
RestartSec=10s
WorkingDirectory=/home/orca
ExecStart=/usr/bin/python3 -m mail_send.py
[Install]
WantedBy=multi-user.target
systemctl コマンドでpythonスクリプトサービスを実行する。