function Sidebar() { return ( ); }

Step-by-Step Guide How to send a E-Mail with Python and Gmail

...


Here I show you how to set up a reverse proxy server with Apache2


Today I'll show you how you can send automated emails with Python and a Gmail (Google) account.

Benefits of Sending Automated Emails with Python

Automating emails using Python offers numerous advantages, from saving time to enhancing productivity and communication. By leveraging Python scripts to manage emails, you can streamline repetitive tasks, improve responsiveness, and maintain consistent communication effortlessly.

Key Advantages of Automated Emailing

  • Time Efficiency: Automated emails reduce manual work by handling tasks like sending routine updates, reminders, and follow-ups, freeing up time for other priorities.
  • Consistency in Communication: With automation, you ensure messages are sent on time, whether it's daily summaries, monthly reports, or customer notifications. This maintains a consistent communication schedule.
  • Improved Accuracy: Automation minimizes human error, ensuring that the right information reaches the intended recipients without mistakes like missed messages or incorrect recipients.
  • Customizable Messaging: Python allows dynamic content generation, so emails can be personalized with names, account details, or specific data points, enhancing relevance for each recipient.
  • Enhanced Scalability: Automating emails makes it easier to manage larger communication needs, such as sending out updates to hundreds of users without the need for manual intervention.

Common Use Cases for Automated Emails

  • Regular Updates: Automated scripts can send daily, weekly, or monthly summaries or status reports to keep everyone informed.
  • Customer Notifications: Common for sending order confirmations, shipping updates, or reminders for expiring subscriptions.
  • Internal Alerts: Use Python scripts to notify your team about critical issues, system statuses, or other immediate information.
  • Appointment Reminders: Automating reminders for meetings or appointments reduces the risk of missed engagements and keeps schedules organized.
  • Personalized Marketing: Automated emails can include customized promotions or offers based on user preferences, enhancing customer engagement.

Let us start!

1. Enable Two-Factor Authentication (2FA)

  • Two-Factor Authentication is necessary to generate an App Password for enhanced security.
  • Activate 2-way authentication.

2. Generate an App Password

  • Log in to your Google Account.
  • Navigate to the Security section.
  • Under Signing in to Google, locate and click on App Passwords (this option is available only if 2FA is enabled).
  • Select App Passwords and enter your account credentials if prompted.
  • Under Select app, choose Mail. Then, under Select device, choose Other (Custom name) and enter a name like “Python Script” before clicking Generate.
  • A 16-character App Password will be displayed. Copy this code and use it in place of your regular password in the Python script.

3. Use the App Password in Your Code

Replace the current app_password in your code with the newly generated App Password. Ensure this password is stored securely and not shared publicly.


Python Code


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email():
    # Gmail Account Data
    sender_email = "yourMailFromYourAccount@gmail.com"  # Your Gmail address
    receiver_email = "receiver@gmail.com"
    subject = "Test E-Mail with App Password"
    body = "This is a test email!"
    
    # Your App Password (generated from Google)
    app_password = "yourGeneratedCode"

    # Create the email content
    message = MIMEMultipart()
    message['From'] = sender_email  # Use your actual Gmail address
    message['To'] = receiver_email
    message['Subject'] = subject
    message.attach(MIMEText(body, 'plain'))

    # Configure Gmail SMTP server and send email
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()  # Enable secure connection
            server.login(sender_email, app_password)  # Login with your account
            server.sendmail(sender_email, receiver_email, message.as_string())
        print("Email sent successfully!")
    except Exception as e:
        print(f"Error sending email: {e}")

send_email()

Customize the code with your data