Skip to content

Instantly share code, notes, and snippets.

@hustshawn
Created December 12, 2016 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hustshawn/64a40087282b24ca57102407db47e6f2 to your computer and use it in GitHub Desktop.
Save hustshawn/64a40087282b24ca57102407db47e6f2 to your computer and use it in GitHub Desktop.
Sending email with plain python
import os
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def main():
sender = 'sender@gmail.com'
sender_pwd = '********'
smtp_server = 'smtp.gmail.com'
recievers = [ 'user1@gmail.com', 'user2@gmail.com']
message = MIMEMultipart()
message['Subject'] = 'The email subject'
message['From'] = sender
message['To'] = ''
message['Cc'] = ''
message['Bcc'] = ','.join(recievers)
mail_body = '''
Hi there,
This is the email body.
Test smtp
'''
message.attach(MIMEText(mail_body, 'plain', 'utf-8'))
attach_file_path = './the-attach-file.txt'
attach_file = open(attach_file_path, 'rb')
attach_part = MIMEApplication(attach_file.read(), Name=os.path.basename(attach_file_path))
attach_part['Content-Disposition'] = 'attachment: filename="%s"' % \
os.path.basename(attach_file_path)
attach_file.close()
message.attach(attach_part)
try:
smtp = smtplib.SMTP_SSL()
smtp.connect(smtp_server)
smtp.login(sender, sender_pwd)
smtp.sendmail(sender, recievers, message.as_string())
smtp.close()
except Exception as e:
print(e)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment