Search code examples
pythonpython-3.xsmtplib

Troubleshooting smtplib with cPanel email - Python3


I have tested the below code with gmail credentials and it works perfectly, however, when I try to use an email created within a cPanel it does not work. I am certain that the credentials are correct and that I am not being blocked by the server as my email client is working and I can telnet to it. Is there a way to somehow produce logs to see why exactly it's failing? Using print statements I found that it fails when it gets to the server variable.

import config
import smtplib


class EmailAlert(object):
    """Class for sending email alert from slave account"""
    def __init__(self, subject, msg):

        self.subject = subject
        self.msg = msg

    def send_email(self):
        try:
            server = smtplib.SMTP(config.OUTGOING_SERVER) #It fails here and goes to except
            server.ehlo()
            server.starttls()
            server.login(config.FROM_EMAIL_ADDRESS, config.PASSWORD)
            message = 'Subject: {}\n\n{}'.format(self.subject, self.msg)
            server.sendmail(config.FROM_EMAIL_ADDRESS,
                            config.TO_EMAIL_ADDRESS,
                            message)
            server.quit()
            print("Success: Email sent!")
        except:
            print("Email failed to send.")

email = EmailAlert("Test", "test")
email.send_email()

Solution

  • I found that using port 587 works even though the port shown in cPanel's is usually 465.