Issue when trying to send emails through Python - python-3.x

OS: MacCatalinva V10.15.3
Python: 3.7.7
PiP: 20.0.2
Hey,
I'm new to coding so I'm not sure what this really means.
I'm trying to send emails via Python through Gmail, I've set my account to accept "Less secure app access" and followed the steps in this guide, but all I get is the following:
`[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 354, in send
self.sock.sendall(s)
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mymac/Desktop/Test2.py", line 34, in
server.quit()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 984, in quit
res = self.docmd("quit")
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 420, in docmd
self.putcmd(cmd, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 367, in putcmd
self.send(str)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 357, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected`
And this is my Code:
import smtplib
import ssl
sender_email = "myemailadress#gmail.com"
receiver_email = "myadress#hotmail.com"
message = """\
Subject: Hi there
This message is sent from Python."""
# Send email here
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "myemailadress#gmail.com"
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)
# TODO: Send email here
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()

1)After this line:
server.login(sender_email, password)
make sure to send the message you have it.
For that:
server.sendmail(sender_email,receiver_email,message)
that's it, I hope.

Related

How to solve SMTPSenderRefused(code, resp, from_addr) error?

I am trying to send logs to email address using SMTPHandler in logging.But I got an error like below:
--- Logging error ---
Traceback (most recent call last):
File "/home/ab/anaconda3/envs/ei/lib/python3.9/logging/handlers.py", line 1065, in emit
smtp.send_message(msg)
File "/home/ab/anaconda3/envs/ei/lib/python3.9/smtplib.py", line 986, in send_message
return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
File "/home/ab/anaconda3/envs/ei/lib/python3.9/smtplib.py", line 887, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (530, b'5.7.0 Must issue a STARTTLS command first. b7-20020a170903228700b0017a0668befasm5585565plh.124 - gsmtp', 'None')
Call stack:
File "/home/ab/pa/par/processing.py", line 34, in <module>
logger.info("==========Script started to Run================")
Message: '==========Script started to Run================'
Arguments: ()
Code:
from environs import Env
import logging,logging.handlers
# Log file configuration setting Starts
MAIL_ID = os.environ.get("MAIL_ID")
MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD")
cwd = os.getcwd()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
l_format = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
log_file = logging.FileHandler(cwd + "/cron_tab_log.log")
log_file.setFormatter(l_format)
logger.addHandler(log_file)
smtp_handler = logging.handlers.SMTPHandler(mailhost=('smtp.gmail.com',25),
fromaddr=MAIL_ID,
toaddrs=['ab#gmail.com', 'a#gmail.com'],
subject='Running Log',
credentials=(MAIL_ID,MAIL_PASSWORD),
secure=())
smtp_handler.setLevel(logging.DEBUG)
smtp_handler.setFormatter(l_format)
logger.addHandler(smtp_handler)
# Log file configuration setting Ends
Can anyone suggest a solution to solve this issue?

flask mail error “SMTPServerDisconnected('please run connect() first')”

I am writing a little web application based on Miguel Grinberg's Flasky. I use the exact same code for user send reset password mail using gmail.
The following as my email.py file here i can implement mail sending function
def send_password_reset_email(user):
token = user.get_reset_password_token()
send_email(_('[Microblog] Reset Your Password'),
sender=current_app.config['ADMINS'][0],
recipients=[user.email],
text_body=render_template('email/reset_password.txt',
user=user, token=token),
html_body=render_template('email/reset_password.html',
user=user, token=token))
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
Thread(target=send_async_email,
args=(current_app._get_current_object(), msg)).start()
In routes.py file im getting email from the user and if the user email match then i well send the token to the user via mail
#bp.route('/reset_password_request', methods=['GET', 'POST'])
def reset_password_request():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = ResetPasswordRequestForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
send_password_reset_email(user)
flash(
_('Check your email for the instructions to reset your password'))
return redirect(url_for('auth.login'))
return render_template('auth/reset_password_request.html',
title=_('Reset Password'), form=form)
#bp.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_password(token):
if current_user.is_authenticated:
return redirect(url_for('main.index'))
user = User.verify_reset_password_token(token)
if not user:
return redirect(url_for('main.index'))
form = ResetPasswordForm()
if form.validate_on_submit():
user.set_password(form.password.data)
db.session.commit()
flash(_('Your password has been reset.'))
return redirect(url_for('auth.login'))
return render_template('auth/reset_password.html', form=form)
In model.py file in the user model i generate a token for a user and also check the user token
def get_reset_password_token(self, expires_in=600):
return jwt.encode(
{'reset_password': self.id, 'exp': time() + expires_in},
current_app.config['SECRET_KEY'],
algorithm='HS256').decode('utf-8')
#staticmethod
def varify_reset_password_token(token):
try:
id = jwt.decode(token, current_app.config['SECRET_KEY'],
algorithms=['HS256'])['reset_password']
except:
return
return User.query.get(id)
my flask mail setup is as follows config.py file
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
ADMINS =['socialtraffic#gmail.com']
The following Error i get in the terminal
Traceback (most recent call last):
File "c:\python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "c:\python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Ijaz Bacha\project\microblog1\app\email.py", line 9, in send_async_email
mail.send(msg)
File "c:\users\ijaz bacha\project\microblog1\venv\lib\site-packages\flask_mail.py", line 492, in send
message.send(connection)
File "c:\users\ijaz bacha\project\microblog1\venv\lib\site-packages\flask_mail.py", line 152, in __exit__
self.host.quit()
File "c:\python38\lib\smtplib.py", line 988, in quit
res = self.docmd("quit")
File "c:\python38\lib\smtplib.py", line 424, in docmd
self.putcmd(cmd, args)
File "c:\python38\lib\smtplib.py", line 371, in putcmd
self.send(str)
File "c:\python38\lib\smtplib.py", line 363, in send
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first
I am also doing the same tutorial and ran into the same problem. I found the answer on Miguel's Blog:
You need two terminal windows.
The first terminal running your local mail server that emulates your emails being sent:
$(venv) python -m smtpd -n -c DebuggingServer localhost:8025
Your main flask terminal window with the following required commands (FLASK_DEBUG=1 is optional but highly recommended for troubleshooting):
$ export FLASK_APP=microblog.py
$ export FLASK_DEBUG=1
$ export MAIL_SERVER=localhost
$ export MAIL_PORT=8025
$ flask run
This solved my problems.
In my experience, a while ago I had a very similar issue that you you were having. After troubleshooting, I found out that my code worked when I would create a mail class, and call function like $mailclass.ehlo etc.
Based on the error its having an issue connecting or staying connected. Try calling the connect methods in the function itself and close of the connection after each email.
I decided to change the following line in the app/__init__.py file:
mail = Mail(app)
with:
mail = Mail()
mail.init_app(app)
Solved the issue for me

Python3 Slack RTMClient in not working behind proxy

I am trying to create a simple Python bot for my project. Everything is working fine on my localhost, but the same code stops working behind the network firewall which needs environment proxy to be set.
from slack import RTMClient
proxy='http://XXXX:NNNN'
token='XXXX'
class Botso():
def __init__(self):
self.proxy=self.get_proxy()
self.rt= RTMClient(
token=token,
connect_method='rtm.start',
proxy=self.proxy
)
def get_proxy(self):
host=socket.gethostname()
if "internal" in host:
return None
elif "XXX" in host:
return proxy
#RTMClient.run_on(event="message")
def say_hello(**payload):
data = payload['data']
web_client = payload['web_client']
if 'text' in data and 'hii' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user'] # This is not username but user ID (the format is either U*** or W***)
web_client.chat_postMessage(
channel=channel_id,
text=f"Hi <#{user}>!"
#thread_ts=thread_ts
)
if __name__ == '__main__':
botso=Botso()
botso.rt.start()
The error I am getting while initializing the RTMClient is
Traceback (most recent call last):
File "botso.py" , in <module>
botso.rt.start()
File "/usr/lib64/python3.6/http/client.py", line 974, in send
self.connect()
File "/usr/lib64/python3.6/http/client.py", line 1407, in connect
super().connect()
File "/usr/lib64/python3.6/http/client.py", line 950, in connect
self._tunnel()
File "/usr/lib64/python3.6/http/client.py", line 929, in _tunnel
message.strip()))
OSError: Tunnel connection failed: 403 Forbidden
I have other code in the same environment which uses the same proxy to send slack messages and works fine bu using request api.
params={
'token': self.slack_token,
'types': ['public_channel','private_channel']
}
slack_url='https://slack.com/api/conversations.list'
response = requests.get(url=slack_url,params=params,proxies=self.proxy).json()
How can we make the RTMClient work with proxy and Python3.
Couldn't find much help in slack API documents.

Why do I get a "No SSL included in this python" when I run script using smtplib from a batch file but not when I run it manually?

I am able to send emails fine from a script using smtplib, but when I try to run it from a batch file or from task scheduler everything works except the email doesn't send at the end. I get a "No SSL" error.
I'm running this from a conda environment, but I've double checked that I calling python from within that environment and not base.
python version 3.7.3.
I call this function from another script and pass the email subject and message to the function.
def send_log_email(subject, message):
smtp_server = 'smtp.office365.com'
smpt_port = 25
sender = '[emailed address]'
pw = '[password]'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = sender
msg['Subject'] = subject
msg.attach(MIMEText(message))
conn = SMTP(smtp_server,smtp_port)
conn.set_debuglevel(1)
conn.starttls()
conn.login(sender, pw)
conn.sendmail(sender, sender, msg.as_string())
Here's the error I get when I run it from a batch file.
send: 'ehlo []\r\n'
reply: b'250-Outlook Hello [IP]\r\n'
reply: b'250-SIZE 157286400\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-DSN\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-STARTTLS\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-BINARYMIME\r\n'
reply: b'250-CHUNKING\r\n'
reply: b'250 SMTPUTF8\r\n'
reply: retcode (250); Msg: b'outlook' Hello [IP]\nSIZE 157286400\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\nSTARTTLS\n8BITMIME\nBINARYMIME\nCHUNKING\nSMTPUTF8'
send: 'STARTTLS\r\n'
reply: b'220 2.0.0 SMTP server ready\r\n'
reply: retcode (220); Msg: b'2.0.0 SMTP server ready'
Traceback (most recent call last):
File "path\my_script.py", line 136, in <module>
send_log_email(result, message)
File "path\my_email_script.py", line 31, in send_log_email
conn.starttls()
File "python_path\custom_environment\lib\smtplib.py", line 756, in starttls
raise RuntimeError("No SSL support included in this Python")
RuntimeError: No SSL support included in this Python
Contrary to most of what I found online, I needed to activate the environment in the batch file to get the script to run properly from task scheduler.
call C:\ProgramData\Anaconda3\Scripts\activate.bat
"C:\my_env_path\python.exe" "C:\my_script_path\my_script.py"
call C:\ProgramData\Anaconda3\Scripts\deactivate.bat
Not sure if I actually need to deactivate the environment or not, but there it is.

authentication issues in sending email via python script

I followed below steps to send email with python script--
import smtplib
smtpUser='sint.15#gmail.com'
smtpPass='1234'
toAdd='ajit#gmail.com'
fromAdd=smtpUser
subject='Python test'
header='To:' +toAdd+'\n'+'From:'+fromAdd+'\n' +'Subject:'+ subject
body='From within a python script'
print( header + '\n'+ body)
s= smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser,smtpPass)
s.sendmail(fromAdd,toAdd,header +'\n' + body)
s.quit()
then the error msg is--
Traceback (most recent call last):
File "C:/Users/129/PycharmProjects/smtp.py", line 34, in <module>
s.login(smtpUser,smtpPass)
File "C:\WinPython-64bit-3.4.4.2\python-3.4.4.amd64\lib\smtplib.py", line 652, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (501, b'5.5.2 Cannot Decode response q9sm74360527pfg.47 - gsmtp')
Process finished with exit code 1
can someone please explain me what is the error, if I am not wrong it is related to google security.
I used this to send an email from a gmail account:
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login(username, password)
s.sendmail(from_mail, to_mail, msg.as_string())
s.quit()
Have a look here. It worked for me.

Resources