I was addicted to specifying multiple destinations for TO, CC, BCC, so make a note Since it is written that the method called send_message can call sendmail () with the message object as an argument, I tried using it. I think it's very convenient.
http://docs.python.jp/3.3/library/smtplib.html
#!/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()
Recommended Posts