Pythonでメール送信

import os.path  # for os.path.basename
import sys
import smtplib

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header

def send_email(
    smtp_server, smtp_port, sender_user, sender_password,
    from_address, to_address, cc_address,
    subject, message, attachment_paths = None
):
    # メールの設定
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To']   = to_address  # カンマ区切りで複数のアドレスを指定可能
    msg['Cc']   = cc_address  # 同様
    msg['Subject'] = Header(subject, 'utf-8')  # 題名に日本語を含む場合の例

    # メール本文
    body = MIMEText(message, 'plain', 'utf-8')
    msg.attach(body)

    # sendmail()に渡すアドレスは分解し、さらにToとCcを全て含める必要がある
    all_recipients = to_address.split(",") + cc_address.split(",")

    try:
        # 添付ファイルが指定されている場合
        if attachment_paths:
            for attachment_path in attachment_paths.split(","):
                attachment = MIMEApplication(open(attachment_path, 'rb').read())
                attachment.add_header('Content-Disposition', 'attachment',
                  filename=os.path.basename(attachment_path))
                msg.attach(attachment)

        smtp_connection = smtplib.SMTP_SSL(smtp_server, smtp_port)
        smtp_connection.login(sender_user, sender_password)
        # smtp_connection = smtplib.SMTP(smtp_server, smtp_port)
        smtp_connection.sendmail(from_address, all_recipients, msg.as_string())
        smtp_connection.quit()
        print("メールが送信されました。")
    except Exception as e:
        print("メールの送信中にエラーが発生しました:", str(e))

##############################################################
# メインなら
if __name__ == "__main__":

    if len(sys.argv) != 6:
        print("Usage: python mysendmail.py to cc subject honbun-file attached-files")
        print("specify '-' if cc or attached-files are empty.")
        sys.exit(1)

    # ToとCcはカンマ区切りで複数指定可能。Ccは"-"と指定された場合空文字列に置き換える
    to_address = sys.argv[1]
    cc_address = sys.argv[2]
    if cc_address == "-":
        cc_address = ""
    subject = sys.argv[3]

    # 本文はファイルから読む。UTF-8で書かれていること。エンコーディングは変更できるかも
    honbun_file = sys.argv[4]
    with open(honbun_file, "r", encoding="utf-8") as f:
        message = f.read()

    # 添付ファイル。カンマ区切りで複数指定可能。"-"と指定された場合空文字列に置き換える
    attachment_paths = sys.argv[5]
    if attachment_paths == "-":
        attachment_paths = ""

    smtp_server = "smtp.nsnhnkmmkk.co.jp"
    smtp_port = "465"
    sender_user = "account_user"
    sender_password = "account_pass"
    from_address = "fromuser@nsnhnkmmkk.co.jp"

    send_email(
      smtp_server, smtp_port, sender_user, sender_password,
      from_address, to_address, cc_address,
      subject, message, attachment_paths
    )

日本語の送信者名を付与する

from email.header import Header

from_name = "送信者氏名"
msg["From"] = f"{Header(from_name, 'utf-8').encode()} <{from_address}>"

Misc. Topics Top

(first uploaded 2024/12/12 last updated 2024/12/12, URANO398)