Preparation Steps
Before writing code, you’ll need an active SMTP account from a provider like Gmail, Outlook, or QQ Mail. Gather the following details: SMTP server address, port number, your email address, and authentication credentials. For sceurity, many providers require enabling access for less secure apps (for older accounts) or generating an app-specific password (for two-factor authentication enabled accounts).
Sending Plain Text Emails
To send a basic text email, use Python’s smtplib for server communication and email modules to construct the message. Here’s a modified implementation:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
# SMTP Server Configuration
smtp_host = 'smtp.gmail.com' # Replace with your provider's SMTP host
smtp_port = 587 # Common ports: 25 (unencrypted), 465 (SSL), 587 (TLS)
sender_email = 'your-account@example.com'
app_password = 'your-app-specific-password' # Use app password for secure access
recipient_emails = ['colleague@example.com', 'client@example.com']
# Construct Email Content
email_body = 'This is an automated notification sent via Python. No action required unless you see this in error.'
message = MIMEText(email_body, 'plain', 'utf-8')
message['From'] = formataddr(('Automated Alert System', sender_email))
message['To'] = ', '.join(recipient_emails)
message['Subject'] = 'Python Automated Notification: System Update'
# Send the Email
try:
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls() # Enable TLS encryption for secure transmission
server.login(sender_email, app_password)
server.sendmail(sender_email, recipient_emails, message.as_string())
print('Plain text email sent successfully!')
except Exception as error:
print(f'Failed to send email: {str(error)}')
Sending HTML Formatetd Emails
For more visually rich notifications, you can send HTML emails by adjusting the MIMEText content type. Here’s how to modify the message construction:
# Replace the message construction section with this
html_body = '''
<p>Hello Team,</p>
<p>Please be advised of the following system updates:</p>
<ul>
<li>Server maintenance scheduled for 2 AM UTC on Friday</li>
<li>New API endpoint now available for user data requests</li>
<li>For details, visit our <a href="https://internal.example.com/updates">internal update portal</a></li>
</ul>
<p>Best regards,<br>The Automation Team</p>
'''
message = MIMEText(html_body, 'html', 'utf-8')
message['From'] = formataddr(('Automated Alert System', sender_email))
message['To'] = ', '.join(recipient_emails)
message['Subject'] = 'HTML Notification: Critical System Updates'
Key Notes:
- Most modern SMTP servers support HTML emails, but always test your HTML code in a browser to ensure proper rendering.
- Avoid using complex CSS that may not be supported by all email clients.
Adding Attachments to Emails
To include files like reports or logs, use the MIMEMultipart class to create a message with multiple parts. Here’s a complete example:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formataddr
# SMTP Configuration (same as before)
smtp_host = 'smtp.example.com'
smtp_port = 587
sender_email = 'your-account@example.com'
app_password = 'your-app-specific-password'
recipient_emails = ['manager@example.com']
# Create Multipart Message
multipart_msg = MIMEMultipart()
multipart_msg['From'] = formataddr(('Report Automation', sender_email))
multipart_msg['To'] = ', '.join(recipient_emails)
multipart_msg['Subject'] = 'Weekly Performance Report Attached'
# Add Email Body
email_body = 'Please find the weekly performance report attached for your review.'
multipart_msg.attach(MIMEText(email_body, 'plain', 'utf-8'))
# Attach File
attachment_path = 'weekly_performance_report.pdf'
with open(attachment_path, 'rb') as file:
attachment_part = MIMEBase('application', 'octet-stream')
attachment_part.set_payload(file.read())
encoders.encode_base64(attachment_part)
attachment_part.add_header(
'Content-Disposition',
f'attachment; filename="{attachment_path}"'
)
multipart_msg.attach(attachment_part)
# Send the Email
try:
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(sender_email, app_password)
server.sendmail(sender_email, recipient_emails, multipart_msg.as_string())
print('Email with attachment sent successfully!')
except Exception as error:
print(f'Failed to send attachment email: {str(error)}')
Key Notes:
- Adjust the MIME type (
application/octet-streamin this example) to match your file type (e.g.,image/jpegfor images,text/csvfor CSV files). - For filenames with non-ASCII characters, use
email.header.Headerto ensure proper rendering across email clients.