Tutorial: Sending an Email using Python

Tutorial: Sending an Email using Python

In this tutorial, we’ll learn how to send emails, including attachments, using Python.

Table of Contents:

  • Setting Up
  • Crafting the Email
  • Sending the Email
  • Using Gmail as the SMTP Server

Setting Up

Before we begin, we need to set up the email configurations:

import smtplib
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

# Email configurations
SMTP_SERVER = 'smtp.your-email-provider.com'
SMTP_PORT = 587  # Common ports: 587 for TLS, 465 for SSL, 25 for non-secure
SENDER_EMAIL = '[email protected]'
SENDER_PASSWORD = 'your-email-password'
RECEIVER_EMAIL = '[email protected]'

Replace the placeholders with your actual email configurations.


Crafting the Email

  1. Creating a Basic Email:
msg = EmailMessage()
msg['From'] = SENDER_EMAIL
msg['To'] = RECEIVER_EMAIL
msg['Subject'] = 'Your Subject Here'
msg.set_content('Your email body text here.')
  1. Adding Attachments:

If you want to attach a file, use the following code:

filename = 'path-to-your-file.txt'
with open(filename, 'rb') as attachment:
    file_data = attachment.read()
    file_type = mimetypes.guess_type(filename)[0]
    file_name = os.path.basename(filename)

msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

Sending the Email

Now that our email is ready, let’s send it:

with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
    server.starttls()  # Upgrade the connection to secure encrypted SSL/TLS
    server.login(SENDER_EMAIL, SENDER_PASSWORD)
    server.send_message(msg)

Using Gmail as the SMTP Server

If you’re using Gmail as your email provider, there are a couple of additional considerations:

  • SMTP Settings for Gmail:
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587  # Use 465 for SSL
  • Less Secure Apps:

For Gmail to allow third-party apps and scripts to send emails, you might need to enable “Less Secure Apps” in your Gmail settings. To enable:

  1. Go to Google Account.
  2. Click on “Security” on the left-hand side.
  3. Scroll down to the “Less secure app access” section.
  4. Toggle the switch to ON.

Note: Always turn off “Less Secure Apps” after you’re done to ensure your account’s security.


Conclusion

Sending emails via Python is straightforward and powerful, especially when integrating into automation tasks, notifications, or reporting systems. Always ensure you’re following best security practices, especially when handling email credentials.

The Complete Codes

import smtplib
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment():
    # Email configurations
    SMTP_SERVER = 'smtp.example.com'  # Your SMTP server
    SMTP_PORT = 587  # Port for SMTP (commonly 587 for TLS, 465 for SSL, 25 for non-secure)
    SENDER_EMAIL = '[email protected]'  # Your email address
    SENDER_PASSWORD = 'yourpassword'  # Your email password
    RECEIVER_EMAIL = '[email protected]'  # Your colleague's email address

    # Create a multipart email
    msg = MIMEMultipart()
    msg['From'] = SENDER_EMAIL
    msg['To'] = RECEIVER_EMAIL
    msg['Subject'] = 'Log File from Latest Run'

    # Email body
    body = 'Dear colleague, attached is the log file from our latest run.'
    msg.attach(MIMEText(body, 'plain'))

    # Attach the file
    filename = 'output.txt'
    with open(filename, 'rb') as attachment:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename= {filename}')
        msg.attach(part)

    # Sending the email
    with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
        server.starttls()  # Upgrade the connection to secure encrypted SSL/TLS
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, msg.as_string())

if __name__ == "__main__":
    send_email_with_attachment()

你可能感兴趣的:(python,开发语言)