Created
December 12, 2016 09:59
-
-
Save hustshawn/64a40087282b24ca57102407db47e6f2 to your computer and use it in GitHub Desktop.
Sending email with plain python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = '[email protected]' | |
sender_pwd = '********' | |
smtp_server = 'smtp.gmail.com' | |
recievers = [ '[email protected]', '[email protected]'] | |
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