杰瑞科技汇

Python如何用代码发送邮件?

Of course! Sending emails with Python is a common task, and the best way to do it is by using the built-in smtplib and email libraries.

Python如何用代码发送邮件?-图1
(图片来源网络,侵删)

Here’s a complete guide, starting with a simple example and then moving to more advanced scenarios like attachments and HTML emails.

Prerequisites: Get Your Email Provider's SMTP Settings

Before you start, you need the SMTP (Simple Mail Transfer Protocol) server details for your email provider. These are not part of Python; they are provided by your email service (like Gmail, Outlook, etc.).

Here are the settings for the most common providers:

Email Provider SMTP Server Address Port (SSL/TLS) Port (STARTTLS) Notes
Gmail smtp.gmail.com 465 587 ⚠️ Important: Gmail requires "Less secure app access" to be ON or you must use an "App Password". For modern security, App Passwords are the recommended method.
Outlook / Hotmail smtp.office365.com 587 587 Also works for smtp.live.com
Yahoo smtp.mail.yahoo.com 465 587
Apple (iCloud) smtp.mail.me.com 587 587

Security Note: Using your main email password in a script can be risky. Many providers now require you to generate an "App Password". This is a 16-digit password that gives third-party apps access to your account without revealing your main password. If you face authentication errors, check if your provider requires an App Password.

Python如何用代码发送邮件?-图2
(图片来源网络,侵删)

The Simplest Example: Sending a Plain Text Email

This script sends an email from your account to another. We'll use Gmail as an example.

import smtplib
from email.message import EmailMessage
# --- Configuration ---
# Replace with your details
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@example.com"
password = "your_gmail_app_password" # Use an App Password if 2FA is enabled
# --- Create the Email Message ---
msg = EmailMessage()
msg['Subject'] = 'Test Email from Python'
msg['From'] = sender_email
msg['To'] = receiver_email
msg.set_content('This is the body of the email. Hello from Python!')
# --- Send the Email ---
try:
    # Using SSL on port 465
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(sender_email, password)
        smtp.send_message(msg)
    print("Email sent successfully!")
except Exception as e:
    print(f"Failed to send email. Error: {e}")

How to Run This:

  1. Replace "your_email@gmail.com" with your email address.
  2. Replace "recipient_email@example.com" with the email you want to send to.
  3. Replace "your_gmail_app_password" with your actual password or App Password.
  4. Save the code as a .py file (e.g., send_email.py).
  5. Run it from your terminal: python send_email.py

Advanced Example: Sending an Email with an Attachment

This example builds on the first one by adding a file attachment.

import smtplib
from email.message import EmailMessage
import os.path
# --- Configuration ---
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@example.com"
password = "your_gmail_app_password"
# --- Create the Email Message ---
msg = EmailMessage()
msg['Subject'] = 'Email with an Attachment'
msg['From'] = sender_email
msg['To'] = receiver_email
msg.set_content('Please find the attached file.')
# --- Add an Attachment ---
# Path to the file you want to attach
attachment_path = 'my_document.pdf' 
# Check if the file exists before attaching
if os.path.exists(attachment_path):
    with open(attachment_path, 'rb') as attachment:
        # Add file as application/octet-stream
        # email.mime.application.MIMEApplication is also an option
        msg.add_attachment(attachment.read(), maintype='application', subtype='octet-stream', filename=os.path.basename(attachment_path))
else:
    print(f"Warning: Attachment file '{attachment_path}' not found.")
# --- Send the Email ---
try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(sender_email, password)
        smtp.send_message(msg)
    print("Email with attachment sent successfully!")
except Exception as e:
    print(f"Failed to send email. Error: {e}")

Example: Sending an HTML Email

You can send rich, formatted emails using HTML. The set_content method is perfect for this.

import smtplib
from email.message import EmailMessage
# --- Configuration ---
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@example.com"
password = "your_gmail_app_password"
# --- Create the Email Message ---
msg = EmailMessage()
msg['Subject'] = 'A Beautiful HTML Email'
msg['From'] = sender_email
msg['To'] = receiver_email
# --- Set the HTML Content ---
html_content = """
<html>
  <body>
    <h1 style="color:blue;">Hello There!</h1>
    <p>This is an <b>HTML email</b> sent from Python.</p>
    <p>You can add <a href="https://www.python.org">links</a> too!</p>
    <img src="https://www.python.org/static/community_logos/python-logo-master-v3-TM.png" alt="Python Logo" width="150">
  </body>
</html>
"""
msg.set_content(html_content, subtype='html') # Set the content type to 'html'
# --- Send the Email ---
try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(sender_email, password)
        smtp.send_message(msg)
    print("HTML email sent successfully!")
except Exception as e:
    print(f"Failed to send email. Error: {e}")

Using Environment Variables for Security (Best Practice)

Hardcoding your password in a script is bad practice. Instead, use environment variables to keep your credentials separate from your code.

Step 1: Set Environment Variables

You can set them in your terminal before running the script.

On Linux or macOS:

export EMAIL_USER="your_email@gmail.com"
export EMAIL_PASS="your_gmail_app_password"

On Windows (Command Prompt):

set EMAIL_USER="your_email@gmail.com"
set EMAIL_PASS="your_gmail_app_password"

Step 2: Modify the Python Script to Use Them

We'll use the os module to access these variables.

import smtplib
import os
from email.message import EmailMessage
# --- Get credentials from environment variables ---
sender_email = os.environ.get('EMAIL_USER')
receiver_email = "recipient_email@example.com" # You can also put this in an env var
password = os.environ.get('EMAIL_PASS')
# --- Basic check ---
if not sender_email or not password:
    print("Error: EMAIL_USER and EMAIL_PASS environment variables not set.")
    exit()
# --- Create and send email ---
msg = EmailMessage()
msg['Subject'] = 'Secure Email from Python'
msg['From'] = sender_email
msg['To'] = receiver_email
msg.set_content('This email was sent using environment variables for security.')
try:
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(sender_email, password)
        smtp.send_message(msg)
    print("Email sent successfully using environment variables!")
except Exception as e:
    print(f"Failed to send email. Error: {e}")

This approach is much more secure and is the standard way to handle secrets in applications.

分享:
扫描分享到社交APP
上一篇
下一篇