LoginSignup
19
19

More than 5 years have passed since last update.

Pythonで複数の宛先にメールを送信する(Python3)

Posted at

TO,CC,BCCに複数の宛先を指定するときハマったのでメモ
send_messageというメソッドはメッセージオブジェクトをそのまま引数にしてsendmail() を呼び出せると書いてあるので使ってみた。
大変便利だと思う。



#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text      import MIMEText

def send_msg(
    from_addr, to_addrs = [], cc_addrs = [], bcc_addrs = [],
    subject = "", body_html = "", body_text = ""):
    msg  = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From']    = from_addr
    msg['To']      = ",".join(to_addrs)

    if cc_addrs !=[]:
        msg['Cc'] = ",".join(cc_addrs)
    if bcc_addrs !=[]:
        msg['Bcc'] = ",".join(bcc_addrs)

    cset = 'utf-8'

    if body_text != "":
        attachment_text = MIMEText(body_text, 'plain', cset)
        msg.attach(attachment_text)

    if body_html != "":
        attachment_html = MIMEText(body_html, 'html' , cset)
        msg.attach(attachment_html)

    smtp_con = smtplib.SMTP('localhost',25)
    smtp_con.set_debuglevel(True)
    smtp_con.send_message(msg = msg)
    smtp_con.close()
19
19
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
19
19