How to add smtp ni simple mail function example

To add SMTP to a simple mail function in Python, you can use the smtplib library. Here's an example:

Step 1: Install the smtplib library

If you haven't already, install the smtplib library using pip:

pip install smtplib

Step 2: Import the smtplib library

In your Python script, import the smtplib library:

import smtplib

Step 3: Set up your SMTP server

You'll need to set up your SMTP server settings, including the server address, port, username, and password. For example:

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
SMTP_USERNAME = '[email protected]'
SMTP_PASSWORD = 'your_password'

Step 4: Create an SMTP object

Create an instance of the smtplib.SMTP class, passing in the SMTP server address and port:

server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

Step 5: Login to the SMTP server

Use the login method to log in to the SMTP server using your username and password:

server.login(SMTP_USERNAME, SMTP_PASSWORD)

Step 6: Set up the email message

Create a dictionary to represent the email message, including the sender, recipient, subject, and body:

msg = {
    'From': '[email protected]',
    'To': '[email protected]',
    'Subject': 'Test email',
    'Body': 'This is a test email sent using SMTP.'
}

Step 7: Send the email

Use the sendmail method to send the email:

server.sendmail(msg['From'], msg['To'], msg['Body'])

Step 8: Close the SMTP connection

Finally, close the SMTP connection using the quit method:

server.quit()

Here's the complete code:

import smtplib

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
SMTP_USERNAME = '[email protected]'
SMTP_PASSWORD = 'your_password'

server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.login(SMTP_USERNAME, SMTP_PASSWORD)

msg = {
    'From': '[email protected]',
    'To': '[email protected]',
    'Subject': 'Test email',
    'Body': 'This is a test email sent using SMTP.'
}

server.sendmail(msg['From'], msg['To'], msg['Body'])

server.quit()

Note that you'll need to replace the placeholders ([email protected], your_password, [email protected]) with your actual email credentials and recipient email address.