Recent Tutorials and Articles
    How to send an Email in Python
    Published on: 22nd September 2018
    Posted By: Sumit Sain

    This tutorial demonstrates Python way of sending mails with both outlook and Gmail account.

    Abstract


    In this tutorial we will send an Email using Outlook and Gmail account.

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
      
    # creates SMTP session
    #smtp_server = smtplib.SMTP('smtp.gmail.com', 587) -- if you are Gmail sender then you can use this
    smtp_server = smtplib.SMTP('smtp-mail.outlook.com', 587) 
      
    # start TLS(Transport Layer Security) for security 
    smtp_server.starttls() 
      
    # Authentication 
    smtp_server.login("Sender_email_address", "senders_password")
    
    from_address = "Sender_email_address"
    to_address = "Receiver_email_address"
    
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "All Programming tutorials(https://www.allprogrammingtutorials.com)"
    msg['From'] = from_address
    msg['To'] = to_address
    
    # Create the body of the message (an HTML version).
    html = """\
    <html>
      <head></head>
      <body>
        <p>Hello!<p><br>
        <p>you can check it out <a href="https://www.allprogrammingtutorials.com">here</a> our "send email using Python" tutorial.</p>
      </body>
    </html>
    """
    
    # Record the MIME type text/html.
    html_content = MIMEText(html, 'html')
    
    # Attach parts into message container.
    msg.attach(html_content)
    print "Preparing"
    
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.
    smtp_server.sendmail(from_address, to_address, msg.as_string())
    
    print "Done"
    smtp_server.quit()
    

     

    Here in above mention code, we are using three modules (smtplib, MIMEMultipart and MIMEText) and all these three modules are part of the basic python librairies, no need to install external librairies.

    Note: If you not able to send email from gmail account then please allow this setting in your gmail account: less secure apps

    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Posted By: Sumit Sain
    Published on: 22nd September 2018

    Comment Form is loading comments...