Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
email   0   38576
How to send email from Python and Django using Office 365

To send email using python script via Office 365, use below code. This code is tried and tested.

import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText



def send_email():
    try:    
        # Create message container - the correct MIME type is multipart/alternative.
        msg = MIMEMultipart('alternative')
        
        msg['From'] = "fromemail@domain.com"
        msg['To'] = "toemail@domain.com"        
        msg['Subject'] = "test subject"
        
        # see the code below to use template as body
        body_text = "Hi this is body text of email"
        body_html = "<p>Hi this is body text of email</p>
        
        # Create the body of the message (a plain-text and an HTML version).
        # Record the MIME types of both parts - text/plain and text/html.
        part1 = MIMEText(body_text, 'plain')
        part2 = MIMEText(body_html, 'html')

        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        msg.attach(part1)
        msg.attach(part2)
        
        # Send the message via local SMTP server.
        
        mail = smtplib.SMTP("smtp.outlook.office365.com", 587, timeout=20)

        # if tls = True                
        mail.starttls()        

        recepient = [toemail@domain.com]
                    
        mail.login(<login>, <password>)        
        mail.sendmail("fromemail@domain.com", recepient, msg.as_string())        
        mail.quit()
        
    except Exception as e:
        raise e


The email contains two body part, HTML and text. You can use Django template in email.

from django.utils.html import strip_tags
from django.template import Context, Template
from django.template.loader import get_template


template = get_template("myapp/sample_template.html")
context = Context(context_data)
body_html = template.render(context_data)			
body_text = strip_tags(body_html)


It is always advisable to store credentials in a separate config file and not to commit that file on Github.

The same code can be used to send an email via Gmail and Google Apps with slight modification.


Use the below settings:

Gmail :

Host : smtp.gmail.com
Port : 587
tls : True


Google Apps:

Host : smtp.gmail.com
Port : 465
tls : False
 

Warning: Do not send too many emails using the python script via Gmail. Your account may be blocked. Daily email limit is 500 or 1000 emails. 

If you are sending more than 500 emails daily, I recommend using Mailgun. They provide nice API and you can send 20000 emails per month for free.

Read also: How to send bulk emails using Mailgun and Python-Django.


email   0   38576
0 comments on 'How To Send Email From Python And Django Using Office 365'

Related Articles:
Accessing Gmail Inbox using Python imaplib module
In this article, we are accessing Gmail inbox using IMAP library of python, We covered how to generate the password of an App to access the gmail inbox, how to read inbox and different category emails, how to read promotional email, forum email and updates, How to search in email in Spam folder, how to search an email by subject line, how to get header values of an email, how to check DKIM, SPF, and DMARC headers of an email...
Sending email with attachments using Python built-in email module
Sending email with attachments using Python built-in email module, adding image as attachment in email while sending using Python, Automating email sending process using Python, Automating email attachment using python...
Adding Email Subscription Feature in Django Application
email subscription feature in django, sending email subscription confirmation mail in django, sending email unsubscribe email in Django, Add subscription feature in Django...
Sending Emails Using Python and Gmail
Python code to send free emails using Gmail credentials, Sending automated emails using python and Gmail, Using Google SMTP server to send emails using python. Python script to automate gmail sending emails, automating email sending using gmail...
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap