Python Forum
SMTP email won't send. Server seems to hang.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SMTP email won't send. Server seems to hang.
#1
Hi!

I'm having problems connecting to and/or sending email through an SMTP server. I've tried everything Google can find, but I'm clearly not understanding something.

When executing the program below, the code executes with no errors, but everything hangs at the end with a message saying the software unexpectedly lost connection with the server. No messages were sent. Here's the code.

Thanks!

Larry

= = =

# Version 0.5

# import email libraries
import smtplib 			        
from email.message import EmailMessage  

# Define variables 
email_to = '[email protected]'    #This is obviously a fake address, but using the real thing doesn't work either. It is properly formatted as a string.
email_from = '[email protected]'   # Same thing, fake, but the correct address doesn't work - also formatted as a string.
email_pw = 'password'              # Yup, another string.

# Read email body text file - this the text of the email I want to send. All data merges are already stored in this file. It is a pure text file.
with open('/Users/larryj/Desktop/temp.txt','r') as file:
    content=file.read()
    
#  Create a text/plain message
msg = EmailMessage()
msg['Subject'] = 'Thank you '
msg['From'] = email_from
msg['To'] = email_to    
msg.set_content(content)     # Content contains the data read from the text file above.

# setup the server
smtp_server = 'secure.emailsrvr.com'      # This is the correct address for Rackspace email
smtp_user = email_from                       # In this case the sender also owns the email account
smtp_password = email_pw

# Send the message - the dashes are ACTUALLY spaces, which this forum removes. They are spaces in the script.
with smtplib.SMTP(smtp_server, 465) as server:  #This is the correct port for SMTP messages on Rackspace email
    server.starttls()           # Upgrades the connection to a secure encrypted SSL/TLS connection
    server.login(smtp_user, smtp_password)
    server.send_message(msg)
buran write Mar-27-2026, 05:00 AM:
No BBcode Answer
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
gmail or other mail servers may require the sender and login encoded base64

In Linux do that in a bash terminal (command line) like this (don't know how in Windows):

Quote:echo -ne "[email protected]" | base64

which will return something like this:
Quote:cGV0ZXJuYW5qaWdtYWlsLmNvb

If necessary set sender and password, using your values:
Quote:sender_email = "cGV0ZXJuYW5qaWdtYWlsLmNvb"
password = "Z3JoYWF3c3J6cWh0"

Same for your app (IMAP) password:

Quote:echo -ne "abcdefghijklmnop" | base64

# QQ smtp server on port 465 works with the email address and IMAP password unencrypted

#! /usr/bin/python3
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate

subject = "Greetings from China!"
# the email can have a plain text body
body_text = """Hi,
my name is Pedro and I am lazy!
Thank you,
Pedro
"""
# or the email can have an html body, which is formatable
html = """\
<!DOCTYPE html>
<html>
<body style="background-color:gold;"><br><br>
<div style="width:75%; border:4px; border-style:solid; border-color: blueviolet; background-color: silver; border-radius: 20px; padding: 20px; font-size:20px;">
<p>Hi,<br><br>
How are you?<br><br>
My name is <strong>Pedro</strong> and I <strong>make emails</strong><br>
  
You can download our product catalogue from here: <br><br>
<a href="http://www.webpage.com/downloads">Download our product catalogue</a><br><br>
 
Thank you,<br><br>
Pedro<br><br>
My email: <a href="mailto:[email protected]">Send me an email</a><br><br>
 
<a href="http://www.webpage.com">Pedro, Bespoke html</a>        
    </p>
 </div>
</body>
</html>
"""

sender_email = "[email protected]"
# better not write your password in the Python
# Use a so-called app-password also called IMAP password: 16 letters like: abcdefghijklmnop
password = input("Type your password and press enter: ")

# attach a PDF
path2pdf = '/home/pedro/babystuff/forAgro/product list.pdf'
print('Opening pdf ... ')
with open(path2pdf, "rb") as attachment:
    filedata = attachment.read()
names = path2pdf.split('/')
fname = names[-1]

receiver_emails = ["[email protected]", "[email protected]", "[email protected]"] 
def send_email(attach, filename, sender, password, receiver, subject, body, server):    
    message = MIMEMultipart()
    # attach the file
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attach)
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename= {filename}",)
    message["From"] = sender
    message["To"] = receiver
    message["Date"] = formatdate(localtime=True)
    message["Subject"] = subject
    message["Bcc"] = receiver  # Recommended for mass emails
    # Add body to email
    message.attach(MIMEText(body, "html"))
    message.attach(part)
    text = message.as_string()
    context = ssl.create_default_context()
    server.sendmail(sender, receiver, text)
    return "OK"

# this worked on QQ smtp, gmail is more difficult, higher security I suppose
port = 465  # or 587 For SL
smtp_server = "smtp.qq.com"
#smtp_server = "smtp.mail.yahoo.com"
context = ssl.create_default_context()
server = smtplib.SMTP_SSL(smtp_server, port, context=context)
server.login(sender_email, password)
count = 1
for e in receiver_emails:
    print(f'Sending email {count} to {e} ... ')
    send_email(filedata, fname, sender_email, password, e, subject, html, server)
    print(f'Email {count} sent to {e} ... ')
    count +=1
server.quit()
print('All done!')
If you are using port 587, try starting this: server.starttls(context=context) and DO NOT use:

server = smtplib.SMTP_SSL(smtp_server, port, context=context)
instead use:
server = smtplib.SMTP(smtp_server, port)
Then you can use your ordinary email address and your IMAP password (not your normal password) tls takes care of encryption.

context = ssl.create_default_context()
server = smtplib.SMTP(smtp_server, port)
server.starttls(context=context)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Paramiko Server -- Exception (server): Error reading SSH protocol banner ujlain 3 13,565 Jul-24-2023, 06:52 AM
Last Post: Gribouillis
  how to send an image from server to client using PICKLE module dafdaf 1 4,450 Jun-02-2020, 01:08 PM
Last Post: nuffink
  Send Email with attachment metro17 4 7,865 Apr-14-2020, 04:59 PM
Last Post: CodeItBro
  how can i send a list of tuples from the server to the client using sockets? dafdaf 1 5,562 Apr-13-2020, 10:51 PM
Last Post: Larz60+
  Send an email Jokoba 0 3,298 Mar-12-2020, 05:30 PM
Last Post: Jokoba
  Help send email by Python using smtplib hangme 6 10,587 Jan-25-2020, 03:31 AM
Last Post: shapeg
  Send smtp message barry 2 4,752 Jan-23-2020, 07:54 AM
Last Post: shapeg
  Send data BMP180 between client and server trought module socket smalhao 0 4,042 Jul-30-2018, 12:56 PM
Last Post: smalhao
  Start tls - Unable to send email darunkumar 7 16,742 May-30-2018, 10:43 AM
Last Post: darunkumar
  Simple send and recive string Server/Client Epilepsy 1 4,048 May-01-2018, 08:17 PM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020