Send email using Python's smtplib

Send email using Python's smtplib

1. Environment

- Windows7
- Python2.7.13

2. What you want to do

--Send an email using python --Set multiple people for destination and Cc --Attach a zip file --Use Japanese for attachment name

3. Program code

import os.path
import datetime
import smtplib
import codecs, collections
import tempfile
import zipfileJPN as zipfile
import unittest, time, re, os, sys,datetime, shutil
import MimeWriter, mimetools, base64, StringIO

from email import Encoders
from email.Utils import formatdate
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def create_message(from_addr, from_addr_name, to_addr, cc_addr, subject, body, mime, attach_file):

    zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
    zip = zipfile.ZipFile(zf, 'w')
    files = os.listdir(attach_file['path'])
    for i in files:
        filename =""
        filename=i
        zip.write(attach_file['path']+"/"+(filename.decode("cp932")).encode("cp932"))
    zip.close()
    zf.seek(0)

    cset = 'utf-8'
    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = from_addr_name+"<"+from_addr+">"
    msg["To"] = to_addr
    msg["Cc"] = cc_addr
    msg["Date"] = formatdate()
    body = MIMEText(body.encode("utf-8"), 'plain', 'utf-8')
    msg.attach(body)

    attachment = MIMEBase(mime['type'],mime['subtype'])
    attachment.set_payload(zf.read())
    Encoders.encode_base64(attachment)
    msg.attach(attachment)
    attachment.add_header("Content-Disposition","attachment", filename=attach_file['name'])
    return msg

def send(from_addr, to_addrs, cc_addrs, msg):
    smtp = smtplib.SMTP("localhost:host")#Change required
    smtp.sendmail(from_addr, to_addrs+cc_addrs, msg.as_string())
    smtp.close()

if __name__ == '__main__':
    from_addr="[email protected]"
    from_addr_name = "test"
    to_addr = "[email protected],[email protected]"
    cc_addr = "[email protected],[email protected]"
    subject = u"test"
    body = u"test"
    mime={'type':'application', 'subtype':'zip'}
    attach_file={'name':'FileName.zip', 'path':'D://test/File'}
    msg = create_message(from_addr, from_addr_name, to_addr, cc_addr, subject, body, mime, attach_file)
    send(from_addr,to_addr_list, cc_addr_list, msg)

4. Description

1. Send an email using python

--I sent an email using smtplib of python. --smtp = smtplib.SMTP ("localhost: host") with smtp server name and host --You can send an email by writing smtp.sendmail (sending email address, destination email address, contents of the email) and sending it.

def send(from_addr, to_addrs, cc_addrs, msg):
    smtp = smtplib.SMTP("localhost:host")#Change required
    smtp.sendmail(from_addr, to_addrs+cc_addrs, msg.as_string())
    smtp.close()

2. Set multiple people for destination and Cc

--Write in to_addrs + cc_addrs of smtp.sendmail (from_addr, to_addrs + cc_addrs, msg.as_string ()) as a string like "[email protected],[email protected], [email protected]" ( A string of destination names separated by commas) --Please note that if you enter the wrong address, it may be sent only to the beginning.

3. Attach the zip file

--Write the files in the target folder in zip format --Set MIME type and set as attachment --I created a zip file in advance, set the MIME type to zip and sent it, but I was able to send it, but the file may be corrupted.

  zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
    zip = zipfile.ZipFile(zf, 'w')
    files = os.listdir(attach_file['path'])
    for i in files:
        filename =""
        filename=i
        zip.write(attach_file['path']+"/"+(filename.decode("cp932")).encode("cp932"))
    zip.close()
    zf.seek(0)

4. Use Japanese for attachment names

--Since the zipfile.write (file path) function of python2.7 is converted to UTF-8, if you use the Japanese file name as it is, you cannot specify the file. --Correspond by modifying the library, creating it as a new library, and importing it. --Copy zipfile.py in C: \ Python27 \ Lib, create it as a file with a new name, change utf-8 to cp932 (Japanese character code of Windows) and save it.

import zipfileJPN as zipfile

キャプチャ.PNG

Recommended Posts

Send email using Python's smtplib
[boto3] Send an email using SES
[Python] Send email
[Python] Send email
Send email with Django
Try using Python's feedparser.
Send email with Python
Send Japanese email with Python3
Exception handling using Python's ZeroDivisionError
Send email in Python (Outlook)
Send using Python with Gmail
Debug email sending with Python's smtpd.DebuggingServer
Send messages and images using LineNotify
[Automation] Send Outlook email with Python
Generate QR code using Python's "qrcode"
Learn about logging using Python's logging module ①
A story about using Python's reduce
Note: Send an email with Django
Try using Python's networkx with AtCoder
[Python] Send an email with outlook
Send email via gmail with Python 3.4.3.