0
0

Python3: SMTP over SSL でメールの送信

Last updated at Posted at 2024-01-08

こちらのプログラムを改造しました。
Python3: Starttls でメールの送信

mail_send.py
#! /usr/bin/python
#
#	mail_send.py
#
#						Jan/08/2024	
# --------------------------------------------------------------------
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_smtp_ssl import send_smtp_ssl_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!\n'
contents += 'Jan/08/2024 AM 09:38\n'
contents += 'こんにちは。\n'
contents += ' ' + socket.gethostname ()

message = MIMEText (
	contents,
	'plain',
)

message['Subject'] = 'Hello Jan/08/2024 AM 09:39'
message['From'] = mail['from']
message['To'] = mail['to']
message['Date'] = formatdate ()

send_smtp_ssl_proc (mail,message)
#
sys.stderr.write ("*** 終了 ***\n")
# --------------------------------------------------------------------
send_smtp_ssl.py
# -*- coding: utf-8 -*-
#
#	send_smtp_ssl.py
#
#						Jan/08/2024
# --------------------------------------------------------------------
import	sys
import	smtplib
# --------------------------------------------------------------------
# [6-4]:
def send_smtp_ssl_proc (mail,message):
	sys.stderr.write("*** send_smtp_ssl *** start ***\n")
	ss = smtplib.SMTP_SSL (mail['server'],mail['port'])
	ss.ehlo ()
	ss.login (mail['usr'],mail['password'])
	ss.sendmail (
		mail['from'],
		[mail['to']],
		message.as_string (),
		)
	ss.close ()
#
	sys.stderr.write("*** send_smtp_ssl *** end ***\n")
# --------------------------------------------------------------------
.env
SERVER = 'mail.aaaa.co.jp'
PORT = 465
USR = '****@aaaa.co.jp'
PASSWORD = '****'
FROM = '****@aaaa.co.jp'
TO = 'sample@example.com'

実行結果

$ ./mail_send.py

*** 開始 ***
*** send_smtp_ssl *** start ***
*** send_smtp_ssl *** end ***
*** 終了 ***

確認したバージョン

$ python --version
Python 3.11.6
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0