python_wiki:send_email

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python_wiki:send_email [2017/09/02 18:12]
billdozor [The Code]
python_wiki:send_email [2019/05/25 23:50]
Line 1: Line 1:
-====== Send Email ====== 
- 
-**General Information** 
- 
-Sending HTML Supported emails with Python.  
- 
-**Checklist** 
-  * Multiple imports 
- 
----- 
- 
-====== Usage ====== 
- 
-Instructions here. 
-<code bash> 
-Execution code here 
-</code> 
- 
----- 
- 
-====== The Code ====== 
- 
-<code python send-email.py> 
-#======================= 
-# Import Modules 
-#======================= 
- 
-# smtplib: send email 
-import smtplib 
- 
-# MIME: support for html messages 
-from email.mime.multipart import MIMEMultipart 
-from email.mime.text import MIMEText 
- 
- 
-#======================= 
-# CUSTOMIZE HERE 
-#======================= 
-# Send email to/from 
-email_to="system_admins@example.com" 
-email_from="root@system01.example.com" 
- 
- 
-#===================================== 
-# Functions; Main starts after 
-#===================================== 
-# Function: Send email 
-def send_email(send_from, send_to, subject, message): 
- 
-  #--DEBUG--# 
-  #print("\nSend from: " + send_from) 
-  #print("Send to: " + send_to) 
-  #print("Message: " + message) 
- 
-  # Create HTML Supported MIME Type Message 
-  message_container = MIMEMultipart('alternative') 
-  message_container['Subject'] = subject 
-  message_container['From'] = send_from 
-  message_container['To'] = send_to 
- 
-  # Add HTML formatted Message 
-  message_html = MIMEText(message, 'html') 
-  message_container.attach(message_html) 
- 
-  # Send Email 
-  msg = smtplib.SMTP('localhost') 
-  msg.sendmail(send_from, send_to, message_container.as_string()) 
- 
-  return  
- 
- 
-#=================== 
-# Main starts here 
-#=================== 
- 
-# Create HTML formatted message 
-  email_html = """\ 
-<html> 
-<head></head> 
-<body> 
-<b><u>My Email Message</u></b> 
- 
-<p> 
-<b>Hello,</b> 
-<ul> 
-{my_message} 
-</ul> 
- 
-<p> 
-</body> 
-</html> 
-""" 
- 
-  # Variable mappings for email_html string above ( 'label': python_variable ) 
-  email_html_variables = {'my_message': my_prebuilt_message} 
- 
-  # Send Email 
-  print("-> Sending email...") 
-  email_subject = "My Email Subject" 
-  send_email(email_from, email_to, email_subject, email_html.format(**email_html_variables)) 
-</code> 
- 
----- 
  
  • python_wiki/send_email.txt
  • Last modified: 2019/05/25 23:50
  • (external edit)