0

I have written the following code to send an email that simply sends "test" to a specified email address.

 import smtplib
        sentFrom = "my email" 
        to = input("Enter email:  ")
        #numberEmails = raw_input ("Enter number of emails to send")
        messageText = "test"

        msg = "From: %s\n To: %s\n\n%s" % (sentFrom, to, messageText)

        username = str("my email")  
        password = str("my password")  

        try :
            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.ehlo()
            server.starttls()
            server.login(username,password)
            server.sendmail(sentFrom, to, msg)
            server.quit()    
            print (" Email has sent")
        except :
        print("email NOT sent")

When I try to send more emails than 1, for example:

 5*server.sendmail(sentFrom, to, msg)

Only one email sends, then I get the error "email NOT sent." I do not get an "email has sent" after the first email sends, only an "email NOT sent" print after the first. How can I fix this issue? I want to eventually have an input() so I can enter in the number of emails to send, and the program sends the number of emails entered into the input. I put how I think this would look as a comment at the top. Can I just multiply the server.sendmail command by the numberEmails command?

This is my first day using Python so go easy on me pls. :)

1 Answer 1

1

You can't multiply this.

Multiplications can only be done with numbers, server.sendmail(sentFrom, to, msg) does not result in a number.

You're going to have to loop through the amount needed.

So as an example, this prints "hello world" five times:

def test():
    print "hello world"

numberEmails = 5

for _ in range(numberEmails):
    test()

Off course you have to parse your numberEmails to int if it's not an integer.

Eventually you have to loop through this entire block 5 times

try :
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(username,password)
        server.sendmail(sentFrom, to, msg)
        server.quit()    
        print (" Email has sent")
    except :
    print("email NOT sent")
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using a while loop, thanks for the well-written response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.