Sending Emails on GAE through smtp.gmail.com in Python - python-2.7

After reading Google's documentation it should be possible to send an email via smtp.gmail.com on port 465 or 587 on GAE standard.
Reference: https://cloud.google.com/appengine/docs/standard/python/sockets/#limitations_and_restrictions_if_lang_is_java_java_7_runtime_only_endif
What is not documented is how to use the socket library.
I am able to send an email via smtplib running the python script locally.
server = smtplib.SMTP_SSL("smtp.gmail.com", 587)
server.ehlo()
server.login(gmail_access["email"], gmail_access["password"])
server.sendmail(gmail_access["email"], report.owner, msg.as_string())
server.close()
When trying to run the code with GAE's dev_appserver I get the nondescript error "[Errno 13] Permission denied"
Any assistance would be greatly appreciated.

Oddly enough the error only occurs when trying to run the code locally with dev_appserver.py. After deploying the code to App Engine it worked.
import socket
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = gmail_access["email"]
msg["To"] = report.owner
msg.attach(MIMEText(body, "html"))
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.ehlo()
server.login(gmail_access["email"], gmail_access["password"])
server.sendmail(gmail_access["email"], report.owner, msg.as_string())
server.close()

Related

How to solve : [Errno 10060] A connection attempt failed while reading outlook email

import email
import imaplib2
from collections import OrderedDict
import json
EMAIL_USER = 'client#apl.com'
EMAIL_PASSWORD = '*****'
EMAIL_SERVER = 'outlook.office365.com'
def read_mail_from_server():
try:
mail = imaplib2.IMAP4_SSL(EMAIL_SERVER, 993)
mail.login(EMAIL_USER, EMAIL_PASSWORD)
mail.select('INBOX')
typ, raw_data = mail.search(None, 'ALL')
ids_list = len(raw_data[0].split())
print(ids_list)
...
I have written a python code to read outlook emails using imaplib. I'm getting the below error when I run it, but with the same code and with different credentials I was to able to read emails from another server. What could be the reason for getting this 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

localhost is not loading while trying to send mail using flask-mail

The localhost is not running and I am getting an OS:Error of 'No route to host' error when I run the flask app.
I've tried adding this:
app.run(host='0.0.0.0')
but it does not work.Also I have tried changing the port from 5000 to 4996 and various other ports but still I am facing the same issue .
Here is my complete code:
from flask import Flask
from flask_mail import Mail,Message
app = Flask(__name__)
app.config['DEBUG']=True
app.config['TESTING']=False
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT']=456
app.config['MAIL_USE_SSL']=True
#app.config['MAIL_DEBUG']=
app.config['MAIL_USERNAME']='trvt1234#gmail.com'
app.config['MAIL_PASSWORD']='#insert password here'
app.config['MAIL_DEFAULT_SENDER']='trvt1234#gmail.com'
app.config['MAIL_MAX_EMAILS']=None
#app.config['MAIL_SUPRESS_SEND']=
app.config['MAIL_ASCII_ATTACHMENTS']=False
email = Mail(app)
#app.route('/')
def mail():
message = Message('Hello',recipients=['trvt1234#gmail.com'])
email.send(message)
return('message sent successfully')
if __name__ == '__main__':
app.run(host='0.0.0.0')
I am a newbie to Flask and was figuring out how should I go on about this problem.
I think you have the wrong MAIL_PORT - it should be 465 not 456.

Problems using Gmail with Python 2.7

New guy here....
I have searched all over this site and tried multiple variations on my code, but I am still receiving a login error when I attempt to send an email through Gmail using Python 2.7. I have enabled the "less secure apps" thing on my Gmail account and I am still receiving this error:
Traceback (most recent call last):
File "T:\OC\Projects\Aquadat\Scripting\RawArcPyScripts\sendEmailWithAttachment_Aquadat.py", line 28, in
svr.login(sender,pwd)
File "C:\Python27\ArcGIS10.3\lib\smtplib.py", line 615, in login
raise SMTPAuthenticationError(code, resp)
SMTPAuthenticationError: (534, '5.7.14 Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 z33sm11383168qta.48 - gsmtp')
Here is the problematic code. I grabbed a lot of it off of this site and tried to adapt it to my application. Any help would be most appreciated.
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
svr = smtplib.SMTP_SSL('smtp.gmail.com',465)
svr.ehlo()
svr.starttls()
svr.ehlo()
sender = 'my_name'
pwd = 'my_pwd'
svr.login(sender,pwd)
rcvr = sender #Change to arcpy.GetParameterAsText(x) when working
def send_mail(send_from,send_to,subject,text,files,
server):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP_SSL(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()

How to add proxy settings in Paho-MQTT?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Client paho-mqtt MqttServer
# main.py
import paho.mqtt.publish as publish
from json import dumps
from ssl import PROTOCOL_TLSv1
import urllib2
class MqttClient():
host = 'mqtt.xyz.com'
port = '1883'
auth = {}
topic = '%s/streams'
tls = None
def __init__(self, auth, tls=None):
self.auth = auth
self.topic = '%s/streams' % auth['username']
if tls:
self.tls = tls
self.port = '8883'
def publish(self, msg):
try:
publish.single (topic=self.topic,payload=msg,hostname=self.host,
tls=self.tls,port=self.port)
except Exception, ex:
print ex
if __name__ == '__main__':
auth = {'username': 'your username', 'password': ''}
#tls_dict = {'ca_certs': 'ca_certs.crt', 'tls_version': PROTOCOL_TLSv1} # sslvers.
msg_dict={'protocol':'v2','device':'Development Device','at':'now','data':{'temp':21,'hum':58}}
client_mqtt =MqttClient(auth=auth) # non ssl version
#client_mqtt =MqttClient(auth=auth, tls=tls_dict) # ssl version
client_mqtt.publish(dumps(msg_dict))
I guess my organization's proxy settings are blocking the request, so please guide me in including the proxy settings in the above code.
For instance if address is 'proxy.xyz.com' and port number is '0000' and my network username is 'xyz' and password is 'abc'
You haven't mentioned what sort of proxy you are talking about, but assuming you want to use a HTTP proxy.
You can not use a HTTP proxy to forward raw MQTT traffic as the two protocols are not compatible.
If the broker you want to connect to supports MQTT over Websockets then you should be able connect vai a modern HTTP proxy, but this will not work with the code you have posted.
As noted in the comments, The Python Paho client added SOCKS and HTTP proxy support under pull request 315.
Paho community added this feature on 2018.
https://github.com/eclipse/paho.mqtt.python/pull/315
I am adding the code snippet since no one still added it. Just set proxy options for the client object.
client = mqtt.Client()
client.proxy_set(proxy_type=socks.HTTP, proxy_addr=proxy_host, proxy_port=proxy_port)
Your code should something as follow
import socks
import socket
import paho.mqtt.client as mqtt
client = mqtt.Client(client_id='the-client-id')
client.username_pw_set('username', 'password')
# set proxy ONLY after client build but after connect
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_HTTP, addr="proxy.xyz.com", port=0000, rdns=True,username="xyz", password="abc")
socket.socket = socks.socksocket
# connect
client.connect('mqtt.host', port=1883, keepalive=60, bind_address="")
client.loop_forever()
I solved it while using a socks proxy and using PySocks
import socks
import socket
import paho.mqtt.client as mqtt
client = mqtt.Client(client_id='the-client-id')
client.username_pw_set('username', 'password')
# set proxy ONLY after client build but after connect
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "socks.proxy.host", 1080)
socket.socket = socks.socksocket
# connect
client.connect('mqtt.host', port=1883, keepalive=60, bind_address="")
client.loop_forever()

Django EmailMessage not sending/timeout

im trying to use django.core.mail to send emails using the default backend and it doesn't seem to be working. I've set up the email credentials, server, and port number in the settings file but whenever I try to run the send() method of an email message the command hangs indefinitely.
views.py
from django.core.mail import send_mail
def sending_email(request):
message = ""
subject = ""
send_mail(subject, message, from_email, ['to_email',])
Add this in settings.py
# Sending mail
EMAIL_USE_TLS = True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='your gmail account'
EMAIL_HOST_PASSWORD='your gmail password'
I was having the same issue when trying to send via smtp.gmail.com with use_tls=True. It turns out I had the wrong port set. Here's what I'm doing now and it works:
from django.core.mail import get_connection
from django.core.mail.message import EmailMessage
connection = get_connection(use_tls=True, host='smtp.gmail.com', port=587,username='YourEmail#gmail.com', password='YourPassword')
EmailMessage('test', 'test', 'addr#from.com', ['addr#to.com'], connection=connection).send()