python smtp send email code example
Example 1: email in python
import smtplib
from email.message import EmailMessage
EmailAdd = "Email id"
Pass = "Email Password"
msg = EmailMessage()
msg['Subject'] = 'Subject of the Email'
msg['From'] = EmailAdd
msg['To'] = '[email protected]','[email protected]'
msg.set_content('Mail Body')
with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
smtp.login(EmailAdd,Pass)
smtp.send_message(msg)
Example 2: send email python
from mailer import Mailer
mail = Mailer(email='[email protected]', password='your_password')
mail.send(receiver='[email protected]', subject='TEST', message='From Python!')
Example 3: send mail from python
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Example 4: send html smtp email python
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
def send_email():
sender = FROM_EMAIL
receiver = ["[email protected]","[email protected]"]
msg = MIMEMultipart()
msg['From'] = FROM_NAME
msg['To'] = TO_NAME
msg['Subject'] = SUBJECT
with open(HTML_TEMPLATE) as f:
html = f.read()
part = MIMEText(html, 'html')
msg.attach(part)
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(CONNECTION USERNAME/EMAIL, CONNECTION PASSWORD)
connection.sendmail(sender, receiver, msg.as_string())
Example 5: email module python
import smtplib, ssl
smtp_server = "smtp.gmail.com"
port = 587
sender_email = "[email protected]"
password = input("Type your password and press enter: ")
context = ssl.create_default_context()
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email, password)
except Exception as e:
print(e)
finally:
server.quit()