Search code examples
pythonemailsmtplib

smtplib disconnected when sending multiple emails


I am trying to use SMTPlib to send emails using python. I can send a single email in the standard way. Now, I want to send multiple emails, and there should be a way to do it without logging in, and quitting the server every time, before sending an email. I tried the following. I wrapped everything in a SendEmail class, and connected to the server in its init() method:

class SendEmail:

def __init__(self):
    self.username='username@yahoo.com';
    self.password='password';
    self.server=smtplib.SMTP('smtp.mail.yahoo.com',587);
    self.server.starttls();
    self.server.login(self.username,self.password);

Now, I try to use a SendAnEmail() method for the class,to send multiple emails:

def SendAnEmail(self,reciever):
    message='blah';

    try:
        self.server.sendmail(self.username,reciever,message);
        print 'Message Sent'
    except:
        self.server.quit();
        self.server=None;

When I declare an instant of the class, and call SendAnEmail() for the first time, it works. When I call it the second time, it gives me an error, saying that the server is disconnected. Since I have not destroyed the class instance, how is the server getting disconnected? And what is the way around it. Should I connect,login and quit everytime I send an email?

So, in main function:

def main():
    mail0=SendEmail();
    mail0.SendAnEmail('reciever1@yahoo.com');#this works
    time.sleep(60);
    mail0.SendAnEmail('reciever2@yahoo.com');#this does not work

Solution

  • Remove time.sleep(60) - Yahoo won't wait that long (30 seconds?) and will close the connection.

    A couple of other things:

    1. Python does not need semicolons at the end of a line
    2. sendmail() accepts a list of recipients so you can send an email to multiple recipients in one go.