0

When trying to send the email with the host:cpanel.freehosting.com P it is raising an error like

This is my code:

import smtplib
s = smtplib.SMTP('cpanel.freehosting.com', 465)
s.starttls()
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()

This is the error i got:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.5/smtplib.py", line 337, in connect
(code, msg) = self.getreply()
File "/usr/lib/python3.5/smtplib.py", line 393, in getreply
  raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Cheche
  • 1,456
  • 10
  • 27
sivamohan
  • 11
  • 2
  • 2
    Your best bet will be to check with the service provider, ie "does your SMTP server require TLS? Is 465 port the correct port?" etc. I also doubt that this is the correct server url – DeepSpace Jul 13 '18 at 15:12
  • There's quite a bit that goes into making a mail server work. MX Records, Reverse DNS, whitelisting, routing concerns, etc. Are you sure that `cpanel.freehosting.com` is your mail server, for instance? – Adam Smith Jul 13 '18 at 15:17

1 Answers1

1

Considering the port number you are using I'd try with SMTP_SSL instead of SMTP and starttls().

https://docs.python.org/3/library/smtplib.html:

An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used.

STARTTLS is a form of opportunistic TLS, it is supposed to be used with old protocols, that originally did't support TLS, to upgrade the connection. The port 465 was used before the introduction of STARTTLS for SMTPS, which is now deprecated.

import smtplib
s = smtplib.SMTP_SSL('cpanel.freehosting.com', 465)
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()

Alternatively you should be able to use port 25 with your original code.

import smtplib
s = smtplib.SMTP('cpanel.freehosting.com', 25)
s.starttls()
s.login("myusername", "mypassword")
message = "Message_you_need_to_send"
s.sendmail("myemailid", "receiver_email_id", message)
s.quit()

In both examples you can completely omit the port number as you are using the default ports.

smeso
  • 4,165
  • 18
  • 27