Troubleshooting smtplib with cPanel email - Python3 - python

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()

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

Related

How to get a API with email

I'm trying to figure out how to email a person with python and I'm wondering on how to get the api-key.
from socketlabs.injectionapi import SocketLabsClient
from socketlabs.injectionapi.message.bulkmessage import BulkMessage
from socketlabs.injectionapi.message.bulkrecipient import BulkRecipient
from socketlabs.injectionapi.message.emailaddress import EmailAddress
# Your SocketLabs ServerId and Injection API key
client = SocketLabsClient(10000, "YOUR-API-KEY");
message = BulkMessage()
message.plain_text_body = "This is the body of my message sent to %%Name%%"
message.html_body = "<html>This is the HtmlBody of my message sent to %%Name%%</html>"
message.subject = "Sending a test message"
message.from_email_address = EmailAddress("from#example.com")
can someone tell me how to get a api-key or what it is?
I Know How to send emails with Python i can help you with that
import smtplib
import socket
email='Your Email Address'
password='Your Password'
def sendMail(to, message):
#you can replace gmail with type of email you use(outlook, yahoo, etc) but port number(587) is same
try:
server=smtplib.SMTP('smtp.gmail.com', 587)
except socket.gaierror:
print('No Internet')
server.ehlo()
server.starttls()
# if ur login account is gmail then please turn on lesssecure app access at myaccount.google.com/lesssecureapps
server.login(email, password)
server.sendmail('Your Email', to, message)
sendMail('example#outlook.com', 'message')
You have to sign up to socketlabs. Then only you will get an API key for sending the automated email.

Getting error: SMTP AUTH extension not supported by server Python3

when I test below code with server = smtplib.SMTP('smpt.gmail.com:587') it works fine.
But when I change SMTP server to server = smtplib.SMTP('10.10.9.9: 25') - it gives me an error. This SMTP does not require any password.
So what am I missing here?
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd
def send_email(user, recipient, subject):
try:
d = {'Col1':[1,2], 'Col2':[3,4]}
df=pd.DataFrame(d)
df_html = df.to_html()
dfPart = MIMEText(df_html,'html')
user = "myEmail#gmail.com"
#pwd = No need for password with this SMTP
subject = "Test subject"
recipients = "some_recipientk#blabla.com"
#Container
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = user
msg['To'] = ",".join(recipients)
msg.attach(dfPart)
#server = smtplib.SMTP('smpt.gmail.com:587') #this works
server = smtplib.SMTP('10.10.9.9: 25') #this doesn't work
server.starttls()
server.login(user, pwd)
server.sendmail(user, recipients, msg.as_string())
server.close()
print("Mail sent succesfully!")
except Exception as e:
print(str(e))
print("Failed to send email")
send_email(user,"","Test Subject")
IF the server does not require authentication THEN do not use SMTP AUTH.
Remove the following line:
server.login(user, pwd)
Hi I am not entirely sure why it's not working but I have got a few things you can check.
server = smtplib.SMTP('10.10.9.9: 25')
you got a space in the ip:port string, try removing it.
The ip:port combination seems to be from a private LAN address
Try to ping this address to see if you can reach it, If you can't then talk to the person who handles the machine with given ip in your network.
If you can ping the ip, then there is a possibility that the SMTP server is not available on the given port, In that case too contact the person responsible for managing the machine with IP: 10.10.9.9
use given command on terminal
ping 10.10.9.9
Also before login and and sendmail, you should connect to server using connect(), The correct order would be.
server = smtplib.SMTP('10.10.9.9: 25')
server.starttls()
server.connect('10.10.9.9', 465)
server.login(user, pwd)
server.sendmail(user, recipients, msg.as_string())
server.close()
465 is the default port for SMTP server
Thanks,
Let me know If It helped you!

TimeoutError trying to send an email with smtplib

I am trying to use Python's smtplib module to send an email but I keep receiving a TimeoutError.
import smtplib
def send():
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(email, password) # Email and password are already defined
print('Enter recipient: ')
recipient = input()
print('Enter subject:')
subject = input() + '\n'
print('Enter body:')
body = input()
server.sendmail(email, recipient, body)
server.quit()
except TimeoutError as e:
print (str(e))
This code recieves a:
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
It looks like you have not enabled "Allow Less Secure Apps" option in your GMail account.
Here's more officially from Google,
https://support.google.com/accounts/answer/6010255?hl=en
If you are using a VPN connection, disable it first. It worked for me.
Use port 587. I was getting the same error but when I entered 587 as port it worked
smtplib.SMTP("smtp.gmail.com", 587)

Send anonymous mail from local machine

I was using Python for sending an email using an external SMTP server. In the code below, I tried using smtp.gmail.com to send an email from a gmail id to some other id. I was able to produce the output with the code below.
import smtplib
from email.MIMEText import MIMEText
import socket
socket.setdefaulttimeout(None)
HOST = "smtp.gmail.com"
PORT = "587"
sender= "somemail#gmail.com"
password = "pass"
receiver= "receiver#somedomain.com"
msg = MIMEText("Hello World")
msg['Subject'] = 'Subject - Hello World'
msg['From'] = sender
msg['To'] = receiver
server = smtplib.SMTP()
server.connect(HOST, PORT)
server.starttls()
server.login(sender,password)
server.sendmail(sender,receiver, msg.as_string())
server.close()
But I have to do the same without the help of an external SMTP server. How can do the same with Python?
Please help.
The best way to achieve this is understand the Fake SMTP code it uses the great smtpd module.
#!/usr/bin/env python
"""A noddy fake smtp server."""
import smtpd
import asyncore
class FakeSMTPServer(smtpd.SMTPServer):
"""A Fake smtp server"""
def __init__(*args, **kwargs):
print "Running fake smtp server on port 25"
smtpd.SMTPServer.__init__(*args, **kwargs)
def process_message(*args, **kwargs):
pass
if __name__ == "__main__":
smtp_server = FakeSMTPServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
smtp_server.close()
To use this, save the above as fake_stmp.py and:
chmod +x fake_smtp.py
sudo ./fake_smtp.py
If you really want to go into more details, then I suggest that you understand the source code of that module.
If that doesn't work try the smtplib:
import smtplib
SERVER = "localhost"
FROM = "sender#example.com"
TO = ["user#example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Most likely, you may already have an SMTP server running on the host that you are working on. If you do ls -l /usr/sbin/sendmail does it show that an executable file (or symlink to another file) exists at this location? If so, then you may be able to use this to send outgoing mail. Try /usr/sbin/sendmail recipient#recipientdomain.com < /path/to/file.txt to send the message contained in /path/to/file.txt to recipient#recipientdomain.com (/path/to/file.txt should be an RFC-compliant email message). If that works, then you can use /usr/sbin/sendmail to send mail from your python script - either by opening a handle to /usr/sbin/sendmail and writing the message to it, or simply by executing the above command from your python script by way of a system call.

No email sending using smtplib - python

import smtplib
sender = 'den.callanan#gmail.com'
receiver = ['callanden#gmail.com']
message = """From: From Person <den.callanan#gmail.com>
To: To Person <callanden#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
print("trying host and port...")
smtpObj = smtplib.SMTP('smtp.gmail.com', 465)
print("sending mail...")
smtpObj.sendmail(sender, receiver, message)
print("Succesfully sent email")
except SMTPException:
print("Error: unable to send email")
I've created two new email accounts (above), both on the same server (gmail) to test this.
It reaches the point in which it prints "trying host and port..." and does not go any further. So the problem should be with the address and port number I entered. But according to gmail's outgoing mail server details i've inputted them correctly. Any ideas what's wrong?
If I remove the port number or try a different port number such as 587 i'm provided with an error.
Sending email via Gmail's SMTP servers requires TLS and authentication. To authenticate, you will need to make an application-specific password for your account.
This script worked for me (though I used my own GMail email address and my own application-specific password). In the code below, replace APPLICATION_SPECIFIC_PASSWORD with the password you generated.
import smtplib
sender = 'den.callanan#gmail.com'
receiver = ['callanden#gmail.com']
message = """From: From Person <den.callanan#gmail.com>
To: To Person <callanden#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
print("trying host and port...")
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("den.callanan#gmail.com", "APPLICATION_SPECIFIC_PASSWORD")
print("sending mail...")
smtpObj.sendmail(sender, receiver, message)
print("Succesfully sent email")
except smtplib.SMTPException:
print("Error: unable to send email")
import traceback
traceback.print_exc()
(To debug the problem, I added the print-traceback code in the except statement. The exceptions had specific information on how to get it to work. The code hung when accessing port 465, I think because of problems with TLS negotiation, so I had to try using port 587; then I got good debugging info that explained what to do.)
You can see info on the SMTP_SSL object here.

Categories