Search code examples
pythonpython-3.xemailsmtpgmail

Issues with sending emails using an smtp server in python 3.8


I am trying to create an email spammer. I know is is frowned upon but i am running into problems which i cannot seem to solve. I cannot seem to figure out how to:

  1. Define a variable containing a list of emails and add each of them to the recipients list.
  2. Send an email from the google smtp server to that list of emails defined previously.
import smtplib
from email import message



sent = int(0)
while (True):
    sent = sent + 1
    from_addr = '[email protected]' # Must be a gmail adress as the gmail smtp server is used
    to_addr = ['[email protected]', '[email protected]']
    subject = 'test!'
    body = 'test!'

    msg = message.Message()
    msg.add_header('from', from_addr)
    for n in len(to_addr):
        msg.add_header('To') = ', '.join(to_addr[n]) # Add all entries from to_addr as recipients
    msg.add_header('subject', subject)
    msg.set_payload(body)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.login(from_addr, 'insertyourpasswordhere') # This will also generate an error!
    server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
    server.quit()

I don't want the program to send an email to one user in the list at once, i want it to add them all as recipients and then send the email to all of them.

For this code to even have the chance at working, you need to have less safer apps enabled on your gmail account


Solution

  • You have to do the following steps for use gmail's server to send mail:

    1. Turn on the less secure apps
    2. You'll get the security mail in your gmail inbox, Click Yes,it's me in that.
    3. Now run your code again.

    NOTE:Before performing code to required start TLS for security.

    import smtplib 
    from email.message import EmailMessage
    sent = int(0)
    while (True):
        sent = sent + 1
        from_addr = '[email protected]'
        to_addr = ['[email protected]', '[email protected]']
        subject = 'test!'
        body = 'test!'
    
        msg = EmailMessage()
        msg.add_header('from', from_addr)
    
        msg.add_header('To',', '.join(to_addr))
        msg.add_header('subject', subject)
        msg.set_payload(body)
        # creates SMTP session 
        server = smtplib.SMTP('smtp.gmail.com', 587) 
    
        # start TLS for security 
        server.starttls() 
        # Authentication 
        server.login(from_addr, 'insertyourpasswordhere') 
    
        # sending the mail 
        server.send_message(msg, from_addr=from_addr, to_addrs=', '.join(to_addr))
    
        # terminating the session 
        server.quit() 
    

    You change only email and password, above script will run successfully!!