smtplib
is a module in the Python standard library for sending emails via the SMTP protocol. Using smtplib
modules makes it easy to write programs in Python that send mail.
Here are smtplib
some basic steps to send mail using the module:
- Import
smtplib
module:
import smtplib
- Create an SMTP object and connect to the SMTP server:
smtp_server = smtplib.SMTP('smtp.example.com')
In this example, smtp.example.com
is the hostname or IP address of the SMTP server you want to connect to. If the SMTP server needs to use SSL or TLS encryption, use smtplib.SMTP_SSL()
the or smtplib.SMTP()
method starttls()
to enable encryption.
- Log in to the SMTP server:
smtp_server.login('username', 'password')
In this example, username
and password
represent your account name and password on the SMTP server.
- Create a mail object and set the mail content:
from email.mime.text import MIMEText
msg = MIMEText('This is a test email')
msg['Subject'] = 'Test Email'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
In this example, we create a MIMEText object and set the subject, sender, and recipients of the email.
- send email:
smtp_server.sendmail('[email protected]', '[email protected]', msg.as_string())
In this example, we use sendmail()
the method to send the mail to the recipient. The first parameter is the sender's address, the second parameter is a list containing one or more recipient addresses, and the third parameter is a string containing the message content.
- Close the SMTP connection:
smtp_server.quit()
In this example, we use quit()
method close SMTP connection.
This is a very simple example just to demonstrate smtplib
the basic steps of using the module to send mail. When actually sending emails, you may also need to set email attachments, use HTML format, and so on.