Send email to a mailing list using Python

12.2k views Asked by At

I'm trying really hard to check why this is happening but not really sure if its on gmail's server side or in a part of the script I'm using. The problem is that I'm trying to send an email to a mailing list (I have found many posts explaining how to include various emails but none explaining if there is a limitation or workaround to send it to a single email which contains multiple addresses).

In this case I want to send the email to many different people which make part of the BI team of our company ([email protected]), normally sending an email to this address will result in everyone from the team getting the email, but I can't manage to make i work, and I don't want to include all emails in the list because there are too much and it will have to be manually changed every time.

When I try this with another single person email it works perfectly

    import smtplib    

    sender = '[email protected]'
    receivers = ['[email protected]']
    q = ""

    message = """From: Error alert <Server-company>
    To: BI <[email protected]>
    Subject: Error e-mail

    %s
    """ % q

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)
        print "Successfully sent email"
    except SMTPException:
       print "Error: unable to send email"
3

There are 3 answers

1
Hackaholic On

make recivers a list of emails you want to send:

example:
recivers = ['[email protected]','[email protected],...]

try like this:

import smtplib
from email.mime.text import MIMEText
sender = '[email protected]'
receivers = ['[email protected]','b]@company.com'....]
server = smtplib.SMTP('[email protected]',port)
server.starttls()
msg = MIMEText('your_message')
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(receivers)
server.login('username','password')
server.sendmail(sender, recipients, msg.as_string())
server.quit()
0
Johan Garzon On

I finally decided to stick to writing the full list of email addresses inside the list. Apparently if mailing lists are managed locally the re distribution of the emails cant be done.

0
Naphtali Spiegel On

Alright. I found out why this was not working in my organization. Hopefully this can help someone else out. The outlook groups were setup to only work from an internal email address.

Sending emails programmatically, may use a relay method, which has no authentication. As such the email will never go through. The fix is to have the Network ops people (or exchange group) at your company turn on receiving external emails. The emails will then go through.