Automated Email Sender Python, SMTP

👤 Sharing: AI
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(sender_email, sender_password, recipient_email, subject, body, smtp_server='smtp.gmail.com', smtp_port=587):
    """
    Sends an email using SMTP.

    Args:
        sender_email (str): The email address of the sender.
        sender_password (str): The password for the sender's email account.
        recipient_email (str): The email address of the recipient.
        subject (str): The subject of the email.
        body (str): The body of the email.  Can be plain text or HTML.
        smtp_server (str): The SMTP server to use (default: smtp.gmail.com).
        smtp_port (int): The port number for the SMTP server (default: 587 for TLS).
    """

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject

    # Attach the body to the email
    msg.attach(MIMEText(body, 'plain'))  # 'plain' for plain text, 'html' for HTML
    # or msg.attach(MIMEText(body, 'html'))


    try:
        # Connect to the SMTP server
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()  # Upgrade connection to secure TLS
        server.login(sender_email, sender_password)

        # Send the email
        server.sendmail(sender_email, recipient_email, msg.as_string())

        print("Email sent successfully!")
    except Exception as e:
        print(f"Error sending email: {e}")
    finally:
        if 'server' in locals():
            server.quit()  # Close the connection



if __name__ == '__main__':
    # Example usage:  Replace with your actual email details
    sender_email = "your_email@gmail.com"  # Replace with your email address
    sender_password = "your_password"  # Replace with your email password (or app password for Gmail)
    recipient_email = "recipient_email@example.com"  # Replace with the recipient's email address
    subject = "Automated Email from Python"
    body = "This is a test email sent from a Python script.\n\nHave a great day!"

    send_email(sender_email, sender_password, recipient_email, subject, body)


# Example sending an HTML email
# if __name__ == '__main__':
#     sender_email = "your_email@gmail.com"
#     sender_password = "your_password"
#     recipient_email = "recipient_email@example.com"
#     subject = "HTML Email from Python"
#     html_body = """
#     <html>
#       <body>
#         <h1>Hello from Python!</h1>
#         <p>This is an HTML email.</p>
#         <a href="https://www.example.com">Visit our website</a>
#       </body>
#     </html>
#     """
#
#     send_email(sender_email, sender_password, recipient_email, subject, html_body, smtp_server='smtp.gmail.com', smtp_port=587)  #  Specify smtp details if not the default
```
👁️ Viewed: 18

Comments