2020/10/7 Python

Python メールを送信する

SSLを使用する場合

import smtplib
import ssl
from email.mime.text import MIMEText

host = ''
from_addr = ''
to_addr = ''
pwd = ''
subject = ''
message = ''

msg = MIMEText(message)
msg['Subject'] = subject
msg['To'] = to_addr
msg['From'] = from_addr

smtpobj = smtplib.SMTP_SSL(host, 465, context=ssl.create_default_context())
smtpobj.login(from_addr, pwd)
smtpobj.send_message(msg)
smtpobj.close()

STARTTLSを使用する場合

import smtplib
from email.mime.text import MIMEText

host = ''
from_addr = ''
to_addr = ''
pwd = ''
subject = ''
message = ''

msg = MIMEText(message)
msg['Subject'] = subject
msg['To'] = to_addr
msg['From'] = from_addr

smtpobj = smtplib.SMTP(host, 587)
smtpobj.ehlo()
smtpobj.starttls()
smtpobj.ehlo()
smtpobj.login(from_addr, pwd)
smtpobj.send_message(msg)
smtpobj.close()