send SMTP email for office365 with python using tls/ssl - python-2.7

i'm trying to create a python script that sends emails with some messages.
my setup is based on a smtp.office365.com. i created some script to do the job.
#!/usr/bin/python
print ("HI! let's start")
import smtplib
import getpass
port=587
smtp_server="smtp.office365.com"
sender_email='mymail#something.com'
receiver_email='mymail#something.com'
print ("defining server")
server = smtplib.SMTP(smtp_server,port)
password=getpass.getpass("enter password")
message='''
Hi,
THIS IS A TEST MESSAGE.
'''
print ("logging in")
server.login(sender_email,password)
print ("sending mail now")
server_sendmail(sender_email,receiver_email,message)
print ("all must be done by now")
But due to some reasons, it gets stuck after printing "defining server". and never reaches to asking for password. apparently the smtplib.SMTP command hangs. can you tell why this happens and how to get rid of it? my setup is as following :
Server: smtp.office365.com
/sjmail.com
security : STARTTLS
Port : 587

Vishesh Arya!
SMTP AUTH extension not supported by Office 365 account. Search for Microsoft Graph to do this.

Related

fetch website with python include j.s css

i'm trying to fetch a whole website include the JavaScript and css file while using python.
The script get a "GET" request and send back the website (local proxy).
here is my code :
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
opener = urllib.FancyURLopener({})
f = opener.open("http://www.ynet.co.il")
self.wfile.write(f.read())
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ', PORT_NUMBER
# Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
The result for this code is only the html is present to the client.
Thanks a lot for the help, i'm Trying to solve that for few days with no result any .

code runs indefinitely while trying to send mail via python

I am trying to send mail using python via my own setup mail server
import smtplib
SERVER='myserverdomain.com'
server = smtplib.SMTP(SERVER,587)
server.starttls()
server.login(USER,PASS)
server.sendmail(FROM, TO, message)
server.quit()
But when I run the above code after line 3 it is not executing.Kind of like goes into an infinite loop.Why could this be
I am able to ping my server successfully.
import smtplib
SERVER='myserverdomain.com'
server = smtplib.SMTP_SSL(SERVER,587)
server.login(USER,PASS)
server.sendmail(FROM, TO, message)
server.quit()
This answer worked

How to ignore SSL certificate validation in pysimplesoap

I'm trying to access a web service that uses a self-generated certificate using pysimplesoap and python 2.7.9
from pysimplesoap.client import SoapClient
import base64
username = 'webuser'
password = 'webpassword'
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
# real address / login removed
client = SoapClient(wsdl='https://url:port/webservice.asmx?WSDL',
http_headers={'Authorization': 'Basic %s'%base64string}, sessions=True,
cacert=None)
response = client.StatusInfo(... removed ...)
print(response)
Trying this throws the error message
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>
There are tips on how to bypass the problem by fixing urllib2, but is there a simpler way that allows me to tell pysimplesoap to ignore all SSL certificate client side errors. I'm using Windows7 and plan to port the code to a Raspian/Debian Linux, so a solution should not depend on the operating system.
Answering my own question here,
adding the 1st & 3rd line will ignore certification verification
import ssl
from pysimplesoap.client import SoapClient
ssl._create_default_https_context = ssl._create_unverified_context
There's a longer discussion about this here where you can learn why this is not a good idea...

Connect to secure web servive with pfx certificate using python

Hi i need help to get info from web service on secure site with pfx certificate with password.
i tried more then one example..
code example:
import requests
wsdl_url = 'blabla'
requests.get(wsdl_url, cert='cert.pfx', verify=True)
other example:
import urllib3
import certifi
wsdl_url = 'blabla'
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED', # Force certificate check.
ca_certs=certifi.where() # Path to the Certifi bundle.
)
certifi.where()
# You're ready to make verified HTTPS requests.
try:
r = http.request('GET', wsdl_url)
print r
except urllib3.exceptions.SSLError as e:
print "wrong"
# Handle incorrect certificate error.
Error type:
connection aborted
an existing connection was forcibly closed by the remote host
help please

builtin password reset view problem in django1.3

Hi am absolutely new to django,Now I am tring for builtin reset password view..
I follow the link link
But I got the error when I click on reset password button at /password_reset/ :
error at /accounts/password_reset/
[Errno 10061] No connection could be made because the target machine actively refused it.
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
'urls.py'
(r'^accounts/password_reset$','django.contrib.auth.views.password_reset','template_name':'user/password_reset_form.html','email_template_name':'user/password_reset_email.html'}),
(r'^accounts/password/reset/confirm/(?P[0-9A-Za-z]{1,13})-(?P[0-9Aa-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name' : 'user/password_reset.html', 'post_reset_redirect': '/logout/' }),
(r'^accounts/password_reset/done/$',<b>'django.contrib.auth.views.password_reset_done'</b>,{'template_name':'user/password_reset_done.html'}),
(r'^accounts/change_password/$',<b> 'password_change'</b>, {'post_change_redirect' : '/accounts/change_password/done/'}),
(r'^accounts/change_password/done/$',<b> 'password_change_done'</b>,{'template_name':'user/password_change_done.html'}),
<b>password_reset_email.html</b>
{% extends 'base.html'%}
{% block content%}
{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}
{% endblock %}
I add necessary templates in the folder 'user'.Please help me,Thanks in advance.
As rdegges said, it's a connection error. Check which port the request is trying to access, and make sure windows firewall is set up to receive on that port. You can check the port by looking through django's traceback page, and looking at the "local vars".
From the looks of it, it's an email port. Take another look at the traceback and look out for django trying to send a request to port 25. If it does, make sure your port 25 is configured to receive.
Also, you'll need a makeshift SMTP server for testing purposes because you probably wouldn't want to be using a real one. Just have this running in a separate command prompt window while you're running django, and any emails that django tries to send through your port 25 will be saved in an "emails" folder in the working directory.
#/usr/bin/env python
from datetime import datetime
import asyncore
from smtpd import SMTPServer
class EmlServer(SMTPServer):
no = 0
def process_message(self, peer, mailfrom, rcpttos, data):
filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'), self.no)
f = open(filename, 'w')
f.write(data)
f.close()
print '%s saved.' % filename
self.no += 1
def run():
foo = EmlServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
from os.path import exists, join
from os import mkdir, chdir, getcwd
target_directory = join( getcwd(), "emails" )
if exists(target_directory):
chdir(target_directory)
else:
try:
mkdir(target_directory)
except OSError:
from sys import exit
exit("The containing folder couldn't be created, check your permissions.")
chdir(target_directory)
print "Using directory %s" % target_directory
run()
The error you're getting is a connection error--that means that the server you're using to run your Django site is likely not working correctly. Here are some things you can try on your Django server:
If you're running your Django site via python manage.py runserver, you can try to simply re-run that command.
If you're running your site via a webserver like apache, try restarting apache.
If neither of those work, post a comment and let me know what operating system you're running your site on, and how you're running it, and we can do further debugging.