Skip to content

Instantly share code, notes, and snippets.

@haccks
Last active December 23, 2023 13:05
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haccks/4c8d73fbd9fa202c720de9a3c9011483 to your computer and use it in GitHub Desktop.
Save haccks/4c8d73fbd9fa202c720de9a3c9011483 to your computer and use it in GitHub Desktop.
Send emails to multi recipients with multiple attachments using python

A simple script in python3.x to

  • Send text emails.
  • Send to multiple clients.
  • Send multiple attachments (including images, videos, audios and compressed files)

To send email from the local SMTP server (localhost) it is assumed that a mail transfer agent (MTA), like postfix, is already configured on your local system. If not the follow this gist for step by step setup.

To send email from the gmail server you need to allow access for less secure apps in your Google account

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script is designed to send emails to multi recepients from local and other SMTP servers.
Any kind of documents can be attached with the email to be sent.
To send the email from the local SMTP server it is assumed that an email client is already
configured on your local system (postfix, sendmail etc.).
To send the email from gmail server it is necessary to allow "less secure apps"
(https://myaccount.google.com/lesssecureapps) in your Google account
"""
import os
import smtplib
import mimetypes
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
__author__ = 'haccks'
__date__ = 'Oct 16 2018'
def mime_init(from_addr, recipients_addr, subject, body):
"""
:param str from_addr: The email address you want to send mail from
:param list recipients_addr: The list of email addresses of recipients
:param str subject: Mail subject
:param str body: Mail body
:return: MIMEMultipart object
"""
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = ','.join(recipients_addr)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
return msg
def send_email(user, password, from_addr, recipients_addr, subject, body, files_path=None, server='smtp.gmail.com'):
"""
:param str user: Sender's email userID
:param str password: sender's email password
:param str from_addr: The email address you want to send mail from
:param list recipients_addr: List of (or space separated string) email addresses of recipients
:param str subject: Mail subject
:param str body: Mail body
:param list files_path: List of paths of files you want to attach
:param str server: SMTP server (port is choosen 587)
:return: None
"""
# assert isinstance(recipents_addr, list)
FROM = from_addr
TO = recipients_addr if isinstance(recipients_addr, list) else recipients_addr.split(' ')
PASS = password
SERVER = server
SUBJECT = subject
BODY = body
msg = mime_init(FROM, TO, SUBJECT, BODY)
for file_path in files_path or []:
with open(file_path, "rb") as fp:
part = MIMEBase('application', "octet-stream")
part.set_payload((fp).read())
# Encoding payload is necessary if encoded (compressed) file has to be attached.
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(file_path))
msg.attach(part)
if SERVER == 'localhost': # send mail from local server
# Start local SMTP server
server = smtplib.SMTP(SERVER)
text = msg.as_string()
server.send_message(msg)
else:
# Start SMTP server at port 587
server = smtplib.SMTP(SERVER, 587)
server.starttls()
# Enter login credentials for the email you want to sent mail from
server.login(user, PASS)
text = msg.as_string()
# Send mail
server.sendmail(FROM, TO, text)
server.quit()
if __name__ == "__main__":
user = 'USER_NAME' # Email userID
password = 'XXXXXXXX' # Email password
from_addr = 'sender@gmail.com'
recipients_addr = ['recipient1@host.com', 'recipient2@ymail.com', 'recipient3@gmail.com']
subject = 'SMTP mail test'
body = 'Hello from SMTP'
file_path = ['/Path/file.txt', 'image.png', '/Path/clip.mp4']
send_email(user, password, from_addr, recipients_addr, subject, body, file_path)
@edougla8
Copy link

Very useful!

@Aqib-Abbasi
Copy link

i need it in django

@rulerdo
Copy link

rulerdo commented May 18, 2021

thanks for sharing, nice script!

@hunterhec
Copy link

Amazing, thanks for sharing!!

@DarkHacker420
Copy link

can we make the multi-sender Emails and multi-recipients each email send massage only 10 recipients and then go to the next Email for other 10 recipients

@haccks
Copy link
Author

haccks commented Oct 3, 2022

@DarkHacker420 I didn't get you. Can you explain a little more what you are trying to achieve?

@DarkHacker420
Copy link

DarkHacker420 commented Oct 3, 2022 via email

@haccks
Copy link
Author

haccks commented Oct 3, 2022

@DarkHacker420 Yes, it can be done. But why would you want that? To spam?

@DarkHacker420
Copy link

This is possible are not

@haccks
Copy link
Author

haccks commented Oct 3, 2022

@DarkHacker420 It's possible.

@DarkHacker420
Copy link

Can give the example plz how it's work

@haccks
Copy link
Author

haccks commented Oct 3, 2022

@DarkHacker420 It's a bit tricky and time taking. You need to modify send_email method and it will do the magic!

@DarkHacker420
Copy link

Hmm okay

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment