Sending email(outlook as server) in azure databricks notebook in python? - python

I tried to configure using localhost. I ran this in my cmd line.
(python -m smtpd -c DebuggingServer -n localhost:1025)
import smtplib, ssl
smtp_server = "localhost"
port = 1025 # For starttls
sender_email = "my outlook email"
password = input("Type your password and press enter: ")
# Create a secure SSL context
context = ssl.create_default_context()
# Try to log in to server and send email
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
print("server connected")
# TODO: Send email here
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()
But it is giving "connection refused" error.

To resolve connection refused error, you can try following ways:
Firewall might be blocking access to port 1025
Alternatively, you can try using port 25
As per documentation:
For Enterprise Dev/Test subscriptions, port 25 is blocked by default. It is possible to have this block removed. To request to have the block removed, go to the Cannot send email (SMTP-Port 25) section of the Diagnose and Solve blade in the Azure Virtual Network resource in the Azure portal and run the diagnostic. This will exempt the qualified enterprise dev/test subscriptions automatically.
You can refer to Send emails from Azure Databricks

Related

Python SMTPLIB with proxy support, Gmail connection not allowed

I am succesfully sending emails through gmail app password, python and smtplib.
I am attempting to add proxy support to my script, but I am getting hit by the following error message:
socks.GeneralProxyError: Socket error: 0x02: Connection not allowed by ruleset
Here are the relevant parts of my script:
socks.set_default_proxy(socks.SOCKS5, host, port, True, user, passw)
socks.wrapmodule(smtplib)
session = smtplib.SMTP('smtp.gmail.com', 587)
session.login(sender_address, sender_pass)

Connect to a host that doesn't answer to ping

I am trying to connect to a smtp port to automatically send emails through it. The problem is that when trying to connect to it with python smtplib it gives an error that it can't connect to the host. When trying to run nmap with the command
nmap -T4 -p 25,587,465
I get the following output:
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 2.12 seconds
When I add the -Pn option I get the following output:
Host is up.
PORT STATE SERVICE
25/tcp filtered smtp
465/tcp filtered smtps
587/tcp filtered submission
The python script that I have used is:
import smtplib, ssl
port = 465
password = "password"
email = "my#mail"
hostname = "hostname"
context = ssl.create_default_context()
with smtplib.SMTP_SSL(hostname, port, context=context) as server:
server.login(email, password)
And this is the error I get:
TimeoutError: [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
I am running the code on a Windows 10 machine and using Python 3.7.5.
Is there any way for me to connect to one of the email ports and send emails through it through python or c/c++?

Python IMAPlib ErrNo 10060

I'm writing a script to grab the link from an email that my web application sends out to then start off a set of automated tests. At the minute my code should only grab the body of the email, I haven't started to scan for the link within that yet because I get no return.
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('user', 'passwd')
mail.list()
mail.select("inbox")
result, data = mail.search(None, "ALL")
ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]
result, data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1]
print raw_email
I don't see anything wrong in my code for getting the newest email (top of the inbox) and my IMAP is set up for the account. Can anyone enlighten me as to why I'm getting the error:
socket.error: [Errno 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
Thanks in advance.
Edit: Company firewall is blocking port 143 and 993 (default IMAP(S) port), I've posted my workaround as the answer. There is nothing wrong with my code!
To get around the company port restrictions I used the netsh command to port forward an open port to port 993 (default for imaplib's SSL) using the following command in terminal
netsh interface portproxy add v4tov4 listenport=UNBLOCKTHISPORT listenaddress=YOURIP connectport=THISPORTISOPEN connectaddress=YOURIP

Connect to SMTP (SSL or TLS) using Python

I am attempting to connect to the Gmail SMTP mail server and perform tasks as outlined by the skeleton code given to me. Only the use of sockets is allowed (so not the smtplib). I need to: send HELO command, MAIL FROM, RCPT TO, and DATA.
There are many cases of similar problems posted, but they haven't received the proper answer. For example:
Implementing Transport Layer Security in Python - Simple Mail Client
The program is required to connect to smtp.gmail.com over port 587. I've taken two different approaches:
Using STARTTLS:
mailserver = 'smtp.gmail.com'
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((mailserver, 587))
recv = clientSocket.recv(1024)
print recv
if recv[:3] != '220':
print '220 reply not received from server.'
#Send HELO command and print server response
heloCommand = 'HELO Alice\r\n'
clientSocket.send(heloCommand)
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '250':
print '250 reply not received from server.'
#Send MAIL FROM command and print server response.
command = "STARTTLS\r\n"
clientSocket.send(command)
recvdiscard = clientSocket.recv(1024)
print recvdiscard
clientSocket.send("MAIL From: email\r\n")
recv2 = clientSocket.recv(1024)
print recv2
if recv2[:3] != '250':
print '250 reply not received from server.'
Using SSL:
clientSocketSSL = ssl.wrap_socket(clientSocket)
Then clientSocketSSL replaces all instances of clientSocket. The STARTTLS lines are also removed and import ssl is added to the top.
When using the first method, the MAIL FROM: command isn't returning anything. I'm getting the following output:
250 mx.google.com at your service
220 2.0.0 Ready to start TLS
250 reply not received from server.
When using SSL, I'm getting the same as the linked post:
ssl.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Am I missing something here? I guess my best option is to use TLS but I have no idea how to go about that... is there something wrong with my MAIL FROM command?
When using SSL, you need to connect to port 465 instead of port 587. If you use STARTTLS, you still need to use ssl.wrap_socket, you just do it later - specifically, after receiving the 220 response to the STARTTLS command. After doing STARTTLS, you're supposed to do HELO again, since the server is supposed to forget anything that happened before the STARTTLS.
In either case, the servers at smtp.google.com ports 465 and 587 still won't return a 250 response to the MAIL command, since they require that you are authenticated before you send mail. You'll get a 530 response instead. You'll need to use the AUTH command with your gmail.com credentials to authenticate before you can use MAIL successfully on those servers.
If you don't want to authenticate, and depending on the details of what you need to do, you could try using port 25 of the server found in gmail.com's MX record. At the moment, the server is gmail-smtp-in.l.google.com and supports STARTTLS.
After STARTTLS, call
clientSocket = ssl.wrap_socket(clientSocket)

Sending an email via gmail through a python application

as indicated by the title I am having trouble sending an email via my gmail account through a python application.I have searched online for a solution but nothing seems to solve it and I thought I might ask here.
My code is the following:
FROMADDR = "myemail#gmail.com"
LOGIN = FROMADDR
PASSWORD = "mypass"
TOADDRS = "varis81#hotmail.com"
msg = "Test message"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
print "E-mail succesfully sent"
I get the message:
socket.error: [Errno 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
I tried different ports but it doesn't work also.I also tried hotmail but it causes the same problem.I am using Python 2.7 (don't ask :) ) on a Windows 7 machine developing on Eclipse using PyDev.
Any help would be great!
Thank you in advance.
I'm using the same construct on one of my servers. My code is below.
The only difference is the extra .ehlo() after '.starttls()`. This should not be the issue; from the RFC:
5.2 Result of the STARTTLS Command
The client SHOULD send an EHLO command as the first
command after a successful TLS negotiation.
According to the RFC, the server should not sever a connection if the client does not send ehlo after starttls, but Google could be more restrictive on their SMTP server. I'd check that first. (I've seen providers tighten down on these kinds of conditions to reduce spam, see Mailinator's 2007 writeup for instance.)
It could also be filtered ports - try running the code in the REPL and confirm which line is exceptioning, if it's the connect() you'll know it's network. If it's after, it's likely your usage of smtplib.
Of note, I also experienced occasional unclean shutdowns, resulting in the try/except around .close().
import smtplib
s = smtplib.SMTP()
s.connect("smtp.gmail.com")
s.ehlo()
s.starttls()
s.ehlo()
s.login("from#gmail.com", "frompass")
s.sendmail("fromname#gmail.com", toAddr, bytes)
try:
s.close()
except: pass
Well, since I cant post comments yet I'll have to attempt an answer..
Judging by this: Python SMTP Errno 10060
Perhaps a timeout would help?

Categories