Last modified: Jan 10, 2023 By Alexander Williams
Example | Sending an Email in Python
In this article, we'll learn how to send mail in python without any complication.
sending an mail using smtp module
if you would use the Gmail server you must enable POP download and IMAP access in your account settings, you also must enable less secure app access in your settings.
syntax:
import smtplib # importing module
server = smtplib.SMTP()
server.connect('smtp_host','port') # connecting to smtp server
server.ehlo()
server.starttls()
#log in to the server
server.login("username", "password") #logining to smtp server
#Send the mail
msg = 'hello world' #your message
server.sendmail("email_sender", "email_receiver", msg) #sending email
example:
import smtplib
server = smtplib.SMTP()
try:
server.connect('smtp.gmail.com','587')
server.ehlo()
server.starttls()
server.login("my_mail@gmail.com", "my_pass")
msg = 'hello world'
server.sendmail("email0@gmail.com", "example@gmail.com", msg)
# sucess message
print('The mail has been sent')
except Exception as e:
print(e)
output:
The mail has been sent