TPointTech Python Sending Email Send Text, HTML, and Attachments Using SMTP Prepared by Rachit Joshi 1. Introduction Python can send email through an SMTP (Simple Mail Transfer Protocol) server. The built - in smtplib module provides the connection and sending functions, while the email package helps create messages with subjects, plain text, HTML content, and attachments. These tools can be used for notifications, reports, and other legitimate application messages. 2. What Is SMTP? SMTP is a protocol used to submit and relay outgoing email. A Python program connects to an SMTP server, optionally secures the connection with TLS, authenticates when required, and submits a message for delivery. Receiving mail is commonly handled using different protocols, such as IMAP. 3. Python Modules Used for Sending Email • smtplib: connects to an SMTP server and submits messages. • email.message.EmailMessage: builds email messages with headers and content. • ssl: provides a default TLS certificate context for secure connections. • os or environment configuration: can be used to read credentials without hard - coding them. 4. Sending a Plain - Text Email The example below demonstrates the general pattern. Replace the sample server, sender, recipient, and credential settings with values supplied by your email provider. Do not put real passwords in source code. import os import smtplib import ssl from email.message import EmailMessage smtp_host = "smtp.example.com" smtp_port = 587 sender = os.environ["EMAIL_ADDRESS"] password = os.environ["EMAIL_APP_PASSWORD"] recipient = "recipient@example.com" msg = EmailMessage() msg["Subject"] = "Test email from Python" msg["From"] = sender msg["To"] = recipient msg.set_content("Hello! This message was sent using Python.") context = ssl.create_default_context() with smtplib.SMTP(smtp_host, smtp_port) as server: server.ehlo() server.starttls(context=context) server.ehlo() server.login(sender, password) server.send_message(msg) print("Email submitted successfully.") This example uses STARTTLS on port 587, a common configuration. Some providers use implicit TLS on port 465 with smtplib.SMTP_SSL(). Follow the current configuration and authentication requirements of your provider. 5. Understanding the Code EmailMessage() Creates a structured message object. Subject, From, and To Set the main message headers. set_content() Adds a plain - text message body. starttls() Upgrades the SMTP connection to an encrypted TLS connection. login() Authenticates with the provider when required. send_message() Submits the message to the SMTP server. with statement Closes the SMTP connection cleanly when the block finishes. 6. Sending an HTML Email HTML email can include formatting such as headings, links, and bold text. It is good practice to provide a plain - text alternative as well, so that recipients whose email clients do not display HTML can still read the message. from email.message import EmailMessage msg = EmailMessage() msg["Subject"] = "Python HTML email" msg["From"] = sender msg["To"] = recipient msg.set_content("This is the plain - text version of the message.") msg.add_alternative( """ <html> <body> <h2>Hello!</h2> <p>This email contains <strong>HTML formatting</strong>.</p> </body> </html> """, subtype="html" ) Use the same secure SMTP connection pattern from the previous example to send this message with server.send_message(msg). 7. Sending an Email with an Attachment EmailMessage can attach file bytes and specify a MIME type. Always confirm that a file is safe to share and that the recipient is authorized to receive it. from pathlib import Path from email.message import EmailMessage import mimetypes file_path = Path("report.pdf") msg = EmailMessage() msg["Subject"] = "Requested report" msg["From"] = sender msg["To"] = recipient msg.set_content("Please find the requested report attached.") content_type, encoding = mimetypes.guess_type(file_path.name) if content_type is None or encoding is not None: content_type = "application/octet - stream" maintype, subtype = content_type.split("/", 1) msg.add_attachment( file_path.read_bytes(), maintype=maintype, subtype=subtype, filename=file_path.name ) # Send msg using the secure SMTP connection shown earlier. For large files, consider the provider's attachment - size limits and whether a secure file - sharing link is more suitable. 8. Sending to Multiple Recipients recipients = [ "person1@example.com", "person2@example.com" ] msg["To"] = ", ".join(recipients) # Use server.send_message(msg) within the authenticated SMTP session. When sending to many people, consider whether recipients should see one another's addresses. Use a suitable mailing - list or BCC approach when appropriate, and follow applicable privacy and anti - spam requirements. 9. Common Errors and Troubleshooting Authentication failed Check the username, app - specific credentials or supported sign - in method, and provider security settings. Connection timed out Check the SMTP hostname, port, network restrictions, and provider status. TLS or certificate error Use a valid server hostname and the default certificate - verifying SSL context; do not disable certificate checks. Recipient rejected Check the recipient address and the provider's sending policies. Message not found in inbox SMTP acceptance does not guarantee inbox placement. Check spam folders, delivery logs, and sender configuration. 10. Security Best Practices • Never hard - code email passwords or commit them to a public repository. • Use environment variables or a secrets manager to store credentials. • Use TLS and verify server certificates. • Use provider - supported authentication methods; do not rely on outdated 'less secure apps' settings. • Validate recipient addresses and avoid building message headers directly from untrusted input. • Send only messages recipients expect, and follow provider rate limits and anti - spam rules. • Handle exceptions carefully and avoid logging passwords, tokens, or private message content. 1 1 . Conclusion Python's smtplib and email modules make it possible to send plain - text messages, HTML emails, and attachments through an SMTP provider. Use secure connections, provider - approved authentication, protected credentials, and clear error handling to build reliable email features.