Sending mail with through python with roundcube - python

Am trying to send mail with python using my rouncube webmail but when i run it outputs this error 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 checked in my mail and my port is "290" which have provided but when i run the function the mail doesn't send. I know how to send with gmail by turning on less secure app access but don't know how to work around to send with my webmail.
I need your suggestion to work around it.
from smtplib import SMTP_SSL as SMTP
import logging, logging.handlers, sys
from email.mime.text import MIMEText
def send_message():
text = '''
Hello,
Trying to send mail from my webmail in python 3.
Sincerely,
My name
'''
message = MIMEText(text, 'plain')
message['Subject'] = "Email Subject"
my_email = 'joe#mycompany.com'
# Email that you want to send a message
message['To'] = my_email
# You need to change here, depending on the email that you use.
# For example, Gmail and Yahoo have different smtp. You need to know what it is.
connection = SMTP('smtp.roundcube.com', 290)
connection.set_debuglevel(True)
# Attention: You can't put for example: 'your_address#email.com'.
# You need to put only the address. In this case, 'your_address'.
connection.login('fred.kings', 'fredsw321a')
try:
# sendemail(<from address>, <to address>, <message>)
connection.sendmail(my_email, my_email, message.as_string())
finally:
connection.close()
send_message()

I'm using:
Ubuntu 18.04.4 LTS.
Python 3.7.4
Jupyter-Notebook 6.0.1
Anaconda 1.7.2
I can successfully send an email through Python with Roundcube, executing the following script in a jupyter-notebook cell:
import smtplib
email = "myemail#mycompany.com"
password = "mypassword"
to = ["destination#dest.com"]
with smtplib.SMTP_SSL('mail.mycompany.com', 465) as smtp:
smtp.login(email, password)
subject = "testing mail sending"
body = "the mail itself"
msg = "Subject: {}\n\n{}".format(subject, body)
smtp.sendmail(email, to, msg)
I found this information as follows (so you can find yours):
Log into you company email.
Look for the following image and click on it (Webmail Home).
You'll see something like the following:
Scroll down, looking for the following image and click on it (Configure Mail...).
Look for the info at mail server section.
If there are using port 465 (such as in my case) it means that you want to use smtplib.SMTP_SSL instead of smtplib.SMTP.
NOTE: The previous worked for me from my personal computer, however, when I tried to use the same code, from my "virtual machine" at office, it does not work, which makes me think that there is a system limitation, and that the problem is not code-related.
Hope it helps, regards.

Related

Sending e-mail with a Python script deployed on a Linode server using the SMTP library

So I've created a script which sends an update e-mail when the script is finished running. It all works fine locally. But when deployed and ran on a Linode server it doesn't work anymore. Here is the code:
def email(products, new_products, updated_products):
#print(products, new_products, updated_products)
message = EmailMessage()
message.set_content("Products scraped: {}, New products: {}, Updated products: {}".format(products, new_products, updated_products))
message['FROM'] = "e-mail"
message['TO'] = ["e-mail"]
message['SUBJECT'] = "Update"
context = ssl.create_default_context()
#set up SMTP server
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls(context=context)
smtp.login(message['FROM'], "password")
smtp.send_message(message)
smtp.quit()
The error occurs on the line: with smtplib.SMTP('smtp.gmail.com', 587) as smtp. I've tried different ports, but it all results in this error: TimeoutError: [Errno 110] Connection timed out. Has anyone had this problem? Or does anyone have another good way to send an e-mail from a server? Thanks in advance!
Linode block outgoing mail by default to prevent spam.
https://www.linode.com/community/questions/19082/i-just-created-my-first-linode-and-i-cant-send-emails-why-mailing-ports-25-465-a
Try enabling less secure apps for the email id you want to send emails from

How to create a free SMTP server

I am not at all familiar with SMTP but I am working on sending emails through Python code. I have the code but I need to pass SMTP host name for it to actually work. Is there any service which provides a free SMTP service that I leverage for testing out my code? I looked around to create my own SMTP server but couldn't find something that provides a step by step guide to create a SMTP server. I want to create a free server(or if there is any free service) that will provide me with a host name(ip address) so that I can put that host name in my python code and execute it from any machine.
If anyone can point me in the right direction it will be helpful.
import smtplib
username = 'user'
password = 'pwd'
from_addr = 'username#gmail.com'
to_addrs = 'username#gmail.com'
msg = "\r\n".join([
"From: username#gmail.com",
"To: username#gmail.com",
"Subject: subject",
"",
"message"
])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
You can use mutt linux command also here.
See :
https://docs.python.org/3/library/smtplib.html
https://support.google.com/a/answer/176600?hl=en
You need service like https://mailtrap.io/. You'll get SMTP server address (eventually port number) that you point your application to. All e-mails produced by your application will be then intercepted by mailtrap (thus not delivered to the real To: address).
They offer free variant that seems to be suitable for your needs.

Python's smtplib module violating Gmail's terms of use

How can I avoid violating Gmail's terms of use when using Python's smtplib?
I would like to send internal emails using Python. After 2 days of fighting with the Gmail API, I gave up. Then I found the smtplib module, which looked simple and promising.
Following the example here, I wrote this small block of Python code:
import smtplib
# Details of where to send FROM
emailUser = 'an.account.I.made.just.for this.test#gmail.com'
emailPassword = 'password123'
# Send the following message to an address...
message = '[ I am email content ]'
toAddress = 'test.victim#gmail.com'
# Define the HEADER (to, from, and subject)
header = """
To: %s
From: %s
Subject: Python SMTPLIB Test
"""
header = header % (toAddress, emailUser)
# [ Don't know what this does ]
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
# Use User/Password credentials to send email
smtpserver.login(emailUser, emailPassword)
smtpserver.sendmail(emailUser, toAddress, message)
smtpserver.close()
I executed this script. It looks like Google's algorithms must have interpreted this as having been sent with bad intentions, and promptly closed my account! Which is fair enough, as I'm sure smtplib can be abused quite readily. However, I have honest intentions, but I do not know how to get around this issue: how can I avoid violating Gmail's terms of use when using Python's smtplib?
It could be because you are indiscriminately making connections with EHLO, you should be using HELO.
If the server supports EHLO, the client can use EHLO instead of HELO as its first request.
On the other hand, if the server does not support EHLO, and the client sends EHLO, the server will reject EHLO. The client then has to fall back to HELO.
There are a few servers that disconnect when they see EHLO. If the client finds that neither EHLO nor HELO was accepted, for example because the connection was closed, then it has to make a new connection and start with HELO.

Python 2: SMTPServerDisconnected: Connection unexpectedly closed

I have a small problem with sending an email in Python:
#me == my email address
#you == recipient's email address
me = "some.email#gmail.com"
you = "some_email2#gmail.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
# Record the MIME types of both parts - text/plain and text/html.
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('aspmx.l.google.com')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
So before now, my program didn't give me an error, but it also didn't send me an email. And now python gives me an error:
SMTPServerDisconnected: Connection unexpectedly closed
How can I fix this?
TLDR: switch to authenticated connection over TLS.
Most probably the gmail server rejected the connection after the data command (very nasty of them to do so at this stage :). The actual message is most probably this one:
retcode (421); Msg: 4.7.0 [ip.octets.listed.here 15] Our system has detected an unusual rate of
4.7.0 unsolicited mail originating from your IP address. To protect our
4.7.0 users from spam, mail sent from your IP address has been temporarily
4.7.0 rate limited. Please visit
4.7.0 https://support.google.com/mail/answer/81126 to review our Bulk Email
4.7.0 Senders Guidelines. qa9si9093954wjc.138 - gsmtp
How do I know that? Because I've tried it :) with the s.set_debuglevel(1), which prints the SMTP conversation and you can see firsthand what's the issue.
You've got two options here:
Continue using that relay; as explained by Google, it's unencrypted gmail-to-gmail only, and you have to un-blacklist your ip through their procedure
The most fool-proof option is to switch to TLS with authentication
Here's how the changed source looks like:
# skipped your comments for readability
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "some.email#gmail.com"
my_password = r"your_actual_password"
you = "some.email2#gmail.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
part2 = MIMEText(html, 'html')
msg.attach(part2)
# Send the message via gmail's regular server, over SSL - passwords are being sent, afterall
s = smtplib.SMTP_SSL('smtp.gmail.com')
# uncomment if interested in the actual smtp conversation
# s.set_debuglevel(1)
# do the smtp auth; sends ehlo if it hasn't been sent already
s.login(me, my_password)
s.sendmail(me, you, msg.as_string())
s.quit()
Now, if try to 'cheat' the system and send with a different (non-gmail) address it's gonna a) require you to connect to a different hostname (some of the MX records for gmail), then b) stop you and close the connection on the grounds of blacklisted ip, and c) do reverse DNS, DKIM and lots of other countermeasures to make sure you're actually in control of the domain you presented in the MAIL FROM: address.
Finally, there's also option 3) - use any other email relaying service, there are tons of good ones :)
I Had the same issue and solved it just by specifying the right port like this:
smtplib.SMTP('smtp.gmail.com', 587)
Using smtplib.SMTP_SSL() instead of smtplib.SMTP() works for me. Try this.
I have realised a strange behavior. I have used similar codes mentioned both the question and answers. My code has been working for the last days. However, today I encountered the error message mentioned in the question.
My solution:
I had tried my successful attempt via library network. Today I have tried it via Starbucks network (over captive portal). I changed it to my mobile network. It started working again.
Possibly, Google rejects requests from unreliable networks.
I was facing the same problem. In my case, password was changed just few days back. So, it was giving the error. As I updated the password in code, its working like a charm...!!!
Googlers: I had a test smtp server running locally. I was getting this error because I was shutting down the local smtp server before closing the client smtp.
with smtplib.SMTP_SSL("smtp.mail.yahoo.com", port=465) as connection:
connection.login(
user=my_email,
password=my_password
)
connection.sendmail(
from_addr=my_email,
to_addrs=friend_address,
msg=f"Subject:Text\n\n"
f"Body of the text"
)
This is my code. I hope it will be helpful.

Python script should send me mail when there is any exception

I want my Python script to send me mail me when there is any exception. I have tried some code related to SMTP that I found, but unfortunately it's not executing and showing an error. Please help me to find out the main problem.
The SMTP code:
import smtplib
import string
SERVER = 'localhost'
SUBJECT = "Test email from Python"
TO = "abc.def#defghij.com"
FROM = "python#mydomain.com"
text = "Sample of mail"
BODY = string.join(("From: %s" % FROM,"To: %s" % TO,"Subject: %s" %SUBJECT ,"",text), "\r\n")
server = smtplib.SMTP(SERVER) #Here in this line it showing error
server.sendmail(FROM,TO,BODY)
server.quit()
** error message * server = smtplib.SMTP(SERVER)
socket.error: (10047, 'Address family not supported by protocol family: See http://wiki.python.org/jython/NewSocketModule#IPV6addresssupport')
I tested this code with Jython 2.5.3 and Python 2.7 and it works if I change SERVER from localhost to real SMTP server. I took SMTP server address from my email client configuration.
You can try this with yagmail, it will make it all much more convenient:
from yagmail import SMTP
SMTP(FROM).send(TO, SUBJECT, text)
It really requires only that much, and if you do some setup you're registered and safe (no need to write your username and password in script).
Read more about it at github.

Categories

Resources