Skip to content

Instantly share code, notes, and snippets.

@avence12
Last active March 4, 2018 15:20
Show Gist options
  • Save avence12/27d2b9f7435378df3a7fce2f936532b0 to your computer and use it in GitHub Desktop.
Save avence12/27d2b9f7435378df3a7fce2f936532b0 to your computer and use it in GitHub Desktop.
Script to send gmail with attachment
#!/usr/bin/env python
# USAGE: ./sendgmail.py path_to_filename [assigned_attachment_name]
# if not assign assigned_attachment_name, the attachment is named as original path_to_filename
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
import sys
sender = '{YOUR_ID}@gmail.com'
passwd = '{YOUR_PASSWD}'
receivers = ['{RECEIVER_1}@gmail.com','{RECEIVER_2}@gmail.com']
emails = [elem.strip().split(',') for elem in receivers]
msg = MIMEMultipart()
msg['Subject'] = "{YOUR_MAIL_SUBJECT}"
msg['From'] = sender
msg['To'] = ','.join(receivers)
msg.preamble = 'Multipart massage.\n'
part = MIMEText("{YOUR_MAIL_CONTENT}")
msg.attach(part)
part = MIMEApplication(open(str(sys.argv[1]),"rb").read())
if len(sys.argv) > 2:
attachname = str(sys.argv[2])
else:
attachname = str(sys.argv[1])
part.add_header('Content-Disposition', 'attachment', filename=attachname)
msg.attach(part)
smtp = smtplib.SMTP("smtp.gmail.com:587")
smtp.ehlo()
smtp.starttls()
smtp.login(sender, passwd)
smtp.sendmail(msg['From'], emails , msg.as_string())
print 'Send mails to',msg['To']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment