Skip to content
Advertisement

sending random messages with smtplib python

I want to send random messages using smtplib in python, I wrote this code:

import random, string, smtplib


def generator():
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))

def login():
    try:
        global email, server
        email = ''
        pswd = ''
        smtp_server = 'smtp.gmail.com'
        port = 587
        server = smtplib.SMTP(smtp_server,port)
        server.ehlo()
        if smtp_server == "smtp.gmail.com":
            server.starttls()
        server.login(email,pswd)

    except smtplib.SMTPAuthenticationError:
        print('error')

def send():
    try:
        recipient = ''
        message = generator()
        count = 10
        lol = 0
        while lol < count:
            lol+=1
            server.sendmail(email,recipient,message)
            print('done')

    except smtplib.SMTPAuthenticationError:
        print('error')

login()
send()

I’ve received the messages but with the same string, I also tried to make a list of random strings and then make the message variable chose randomly from there using random.choice() but it didn’t work either.

What could the problem be?

Advertisement

Answer

Your mistake: generating one message with message=generator() and using that same message inside the loop. This is why it is always the same string.

You should call generate() every time you iterate through the while loop like this:

count = 10
lol = 0
while lol < count:
    lol+=1
    server.sendmail(email, recipient, generator())
    print('done')

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement