Multi Recipients With smtplib?

Steve Holden sholden at holdenweb.com
Mon Nov 25 09:30:09 EST 2002


"John Abel" <john.abel at pa.press.net> wrote in message
news:mailman.1038231874.18339.python-list at python.org...
> Hi,
>
> I am trying to send a mail, to multiple recipients, without much
> success.  A single mail address works fine, but when I add another,
> using a comma to separate the addresses, the second address fails to
> receive the mail.  Any ideas?  Here's the code I am using:
>
>         mailMessage = "From: %s \r\nTo: %s\r\n" % (self.mailFrom,
> self.mailTo)
>         mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody)
>         try:
>             self.MailConn.sendmail( self.mailFrom, self.mailTo,
mailMessage)
>         except (smtplib.SMTPRecipientsRefused,
> smtplib.SMTPSenderRefused), ErrorMsg:
>             print "There Was A Problem Sending The Mail.  Reason: %s" %
> ErrorMsg
>
> Any help would be appreciated, as this is driving me mad!
>

Given that yout code is arranged to print an error message it's a pity you
didn't give us the benefit of its output so we knew a little more about the
erre that's occurring.

The arguments to the .sendmail() method should be:

    a string containing the sender's address
    a list of strings containing an address for each recipient, and
    an RFC822-formatted mail message

I am guessing that when you say "but when I add another, using a comma to
separate the addresses, the second address fails to receive the mail" you
are setting the self.mailTo attribute to be a comma-separated list ot
recipients? Frankly I'm not sure how you are managing to get this mail
formatted.

What you really want for multiple recipients is something like the
following:


    self.mailFrom = me at mydomain.com
    self.mailTo = ["him at hisdomain.com", "her at herdomain.com",
"it at itsdomain.net"]
    ...
    mailMessage = "From: %s \r\nTo: %s\r\n" \
                % (self.mailFrom, ", ".join(self.mailTo))
    mailMessage += "Subject: %s\r\n%s" % (mailSubject, mailBody)
        try:
            self.MailConn.sendmail( self.mailFrom, self.mailTo, mailMessage)
        except (smtplib.SMTPRecipientsRefused,
                smtplib.SMTPSenderRefused), ErrorMsg:
            print "There Was A Problem Sending The Mail.  Reason: %s" \
                    % ErrorMsg

In other words, use a comma-separated list of recipients in the message
body, but a list of email addresses as the second argument to .sendmail().

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list