hi-ho.ne.jp で試した方法です。
プログラム
hi-ho.py
#! /usr/bin/python
#
# hi-ho.py
#
# Jun/26/2023
# --------------------------------------------------------------------
import os
import sys
import socket
from dotenv import load_dotenv
import email
from email.mime.text import MIMEText
from email.utils import formatdate
# --------------------------------------------------------------------
from send_starttls import send_starttls_proc
# --------------------------------------------------------------------
sys.stderr.write ("*** 開始 ***\n")
dotenv_path = '.env'
load_dotenv(dotenv_path)
mail = {}
mail['server'] = os.environ.get("SERVER")
mail['port'] = os.environ.get("PORT")
mail['usr'] = os.environ.get("USR")
mail['password'] = os.environ.get("PASSWORD")
mail['from'] = os.environ.get("FROM")
mail['to'] = os.environ.get("TO")
contents = 'Hello, Good Afternoon! on Jun/26/2023 from Hi-ho\n'
contents += 'Jun/26/2023 PM 13:34\n'
contents += 'こんにちは。\n'
contents += ' ' + socket.gethostname ()
message = MIMEText (
contents,
'plain',
)
message['Subject'] = 'Hello Jun/26/2023 from Hi-ho'
message['From'] = mail['from']
message['To'] = mail['to']
message['Date'] = formatdate ()
send_starttls_proc (mail,message)
#
sys.stderr.write ("*** 終了 ***\n")
# --------------------------------------------------------------------
send_starttls.py
# -*- coding: utf-8 -*-
#
# send_starttls.py
#
# Jul/05/2020
# --------------------------------------------------------------------
import sys
import smtplib
# --------------------------------------------------------------------
# [6-4]:
def send_starttls_proc (mail,message):
sys.stderr.write("*** send_starttls *** start ***\n")
ss = smtplib.SMTP (mail['server'],mail['port'])
ss.ehlo ()
ss.starttls ()
ss.ehlo ()
ss.login (mail['usr'],mail['password'])
ss.sendmail (
mail['from'],
[mail['to']],
message.as_string (),
)
ss.close ()
#
sys.stderr.write("*** send_starttls *** end ***\n")
# --------------------------------------------------------------------
.env
SERVER = 'hi-ho.mose-mail.jp'
PORT = 587
USR = '****@hi-ho.ne.jp'
PASSWORD = '****'
FROM = '****@hi-ho.ne.jp'
TO = 'sample@example.com'
実行結果
$ ./hi-ho.py
*** 開始 ***
*** send_starttls *** start ***
*** send_starttls *** end ***
*** 終了 ***
確認したバージョン
$ python --version
Python 3.11.6