Search code examples
pythonsmtplib

Sending Email to a Microsoft Exchange group using Python?


I've written a python script to send out emails, but now I'm wondering if it's possible to send emails to Microsoft exchange groups using python? I've tried including the group in the cc and to fields but that doesn't seem to do the trick. It shows up, but doesn't seem to correspond to a group of emails; it's just plain text.

Anyone know if this is possible?


Solution

  • This is definitely possible. Your exchange server should recognize it if you treat it as a full address. For example if you want to send it to person1, person2, and group3, use the following:

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    
    address_book = ['person1@company.com', 'person2@company.com', 'group3@company.com']
    msg = MIMEMultipart()    
    sender = 'me@company.com'
    subject = "My subject"
    body = "This is my email body"
    
    msg['From'] = sender
    msg['To'] = ','.join(address_book)
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    text=msg.as_string()
    #print text
    # Send the message via our SMTP server
    s = smtplib.SMTP('our.exchangeserver.com')
    s.sendmail(sender,address_book, text)
    s.quit()