Pythonからメール送信(添付付き)

from email import message
from email.mime import multipart
from email.mime import text
import smtplib

smtp_host = 'smtp-mail.outlook.com'
smtp_port = 587

from_email = '送信元アドレス'
to_email = '送信先アドレス'
username = 'ユーザー名'
password = 'パスワード'

msg = multipart.MIMEMultipart()
msg['Subject'] = 'Test email sub'
msg['From'] = from_email
msg['To'] = to_email
msg.attach(text.MIMEText('Test email', 'plain'))

with open('添付ファイルする内容テキストと拡張子', 'r') as f:
    attachment = text.MIMEText(f.read(), 'plain')
    attachment.add_header(
        'Content-Disposition','attachment',
        filename='添付ファイル名と拡張子'
    )
    msg.attach(attachment)

server = smtplib.SMTP(smtp_host, smtp_port)
server.starttls()
server.ehlo()
server.login(username, password)
server.send_message(msg)
server.quit()
タイトルとURLをコピーしました