Ask coding questions

← Back to all posts
How do I send email from Python?
AlexZelvin (2)

Did a Google search for how to send email from Python in and tried following the few examples I was able to find. None of them worked.

Here's the code for one of them (I obviously used a real 'fromaddress' and 'password'):
import smtplib
s = smtplib.SMTP('', 587)
s.login('[email protected]', 'password')

msg = email.message.EmailMessage()
msg['from'] = '[email protected]'
msg["to"] = '[email protected]'
msg["Subject"] = "test "
msg.set_content('this is a test')
res = s.send_message(msg)

Here's what I got:
Traceback (most recent call last):
Traceback (most recent call last):
File "", line 10, in <module>
s = smtplib.SMTP('', 587)
Traceback (most recent call last):
File "", line 10, in <module>
s = smtplib.SMTP('', 587)
File "/usr/local/lib/python2.7/", line 256, in init
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python2.7/", line 317, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python2.7/", line 292, in _get_socket
return socket.create_connection((host, port), timeout)

Got similar results from a variety of other samples that I tried to follow.

SixBeeps (5335)

Was there no error message content saying what went wrong, like a "failed to connect to SMTP server" or something?

InvisibleOne (3213)

Well... not sure if this is 100% legal, but here's the code for my spam bot I built to bug my friends with a while ago:

import smtplib, ssl
import traceback
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
from time import sleep
import random
import time

black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
magenta = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"
bright_black = "\033[0;90m"
bright_red = "\033[0;91m"
bright_green = "\033[0;92m"
bright_yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
bright_magenta = "\033[0;95m"
bright_cyan = "\033[0;96m"
bright_white = "\033[0;97m"

print("SPAM BOT 3000")

target = input(bright_cyan+"Target Email:  ")
message_content = input(bright_cyan+"Message for email:  ")
spam_want = input(red+"How many spam would you like to send: ")

email_list = ['[email protected]'] # this was a list so I could use several emails and switch inbetween them

spam_count = 1
count_time = 0
while spam_count < int(spam_want):
  print(green+"You have sent " + red+str(spam_count) + green+' Spam out of: ' + red+str(spam_want) + green+" Spam")
  spam_count += 1
  list_name = ['bob', 'bill', 'tom', 'mike', 'wendle', 'gemmeh', 'got cash', 'meh petco', 'lasan', 'star wars', 'incredible', 'keep', 'geek', 'turbo', 'the', 'rattle', 'roll', 'I', 'Bobert', 'tommy', 'kitty', 'turtle', 'frog', 'elm', 'spam', 'annoying', 'cruel', 'overnight', 'thomas', '', 'hahafunny', 'thisisspam', 'enjoy','moo oo ah ah ah', 'whacka', 'blue', 'red' 'orange', 'incredible', 'ear']
  list_letters = ['a', 'b', 'v', 'c', 'g', 'y','r','d','e','c','t','y','u','i','p','[']
  list_numbers = ['1','2','3','4','5','6','7','8','9','10', '11','12','13','14','15','16','17','18','19','20']
  context = ssl.create_default_context()
  html = """
                      """ + message_content + """</br> 
  message = MIMEMultipart("alternative")
  message["Subject"] = random.choice(list_name) + random.choice(list_letters) + random.choice(list_numbers)
  part2 = MIMEText(html, "html")
    to = target
    username = random.choice(email_list)
    password = 'yougmailpassword' #put your password here
    gmail_server = smtplib.SMTP('', 587)
    gmail_server.login(username, password)
    message["From"] = username
    message["To"] = to
  except Exception as e:
    print(red+"Issue!!! Spam Bot Failed!")
  def send_my_mail():  
        gmail_server.sendmail(username, to, message.as_string())
      except Exception as e:
          print("Email not sent, due to some issues.")
  if spam_want == spam_count:
      print(red+"Spamming Complete")
FloCal35 (671)

lmao @InvisibleOne, yes I remember that. I've used it once or twice