Python application using office365 exchange server timing out - python

I have a Python program that collects about 11K entries from a CORBA database, then uses those entries to parse through about 1,0000 Mb of text files. This entire process normally takes 5-7 minutes. I log into the Exchange365 server before this starts (so that any unusual events can be emailed to the administrator) and then try to email the results to the 'normal' recipients. That last email is failing and the root cause seems to be that I am getting logged off of the Exchange server.
Adding a 'dummy' email about half way through the processing seems to eliminate the timeout, but I'd like to find a more programatic way to accomplish this. Following is a code snippet where I enable the email:
import smtp
import time
pretty_localtime = time.asctime()
smtpserver = smtplib.SMTP("smtp.office365.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
#
try:
smtpserver.login(office365_user,office365_pwd)
except:
msg = ("%s --- FATAL ERROR: Couldn't log into SMTP server.")%pretty_localtime
log_file.write("%s \n"%msg)
print msg
sys.exit()
Has anyone worked through this problem?
***edit** Python error added:
Traceback (most recent call last):
File "piu_billing.py", line 739, in <module>
log_file.write(email_msg)
File "piu_billing.py", line 102, in send_mail
smtpserver.sendmail(office365_user,to,themsg)
File "C:\Python27\lib\smtplib.py", line 719, in sendmail
(code, resp) = self.mail(from_addr, esmtp_opts)
File "C:\Python27\lib\smtplib.py", line 471, in mail
self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
File "C:\Python27\lib\smtplib.py", line 334, in putcmd
self.send(str)
File "C:\Python27\lib\smtplib.py", line 324, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected

Related

"please run connect() first" - On second try

I have a python script that I've been using for the last couple of months without any issues.
On my last attempt of running the script I encountered the "please run connect() first" error.
I've reviewed related questions here, but in my case the behaviour is kinda odd.
The e-mail sending function ran twice (as expected) - but I got the error only for the second function call (running in a loop).
Not sure why it would work for the first function call, but not for the second one.
I'll also say that it's not the first time I'm calling the function twice, but it's the first time it failed on the second call.
Hopfully that someone has an idea what could cause the error, and how to fix it.
Thanks in advance for the help.
smtp_host = 'AWS' // Not the real value
port = 465
message = "my message"
server = smtplib.SMTP_SSL(smtp_host, port, 'email.com')
msg = EmailMessage()
msg.set_content(message)
msg['Subject'] = "maintenance"
msg['From'] = 'test1#email.com'
msg['To'] = 'test2#email.com'
server.login(args.email_name, args.email_passwd)
server.send_message(msg)
server.quit()
Edit:
The same issue happened again, this time I was able to pull out the traceback:
Traceback (most recent call last):
File "/home/jenkins/workspace/NOC_Maintenance_Scheduler_master/NOC_Scripts/Maintenance_Scheduler/SQL_Email.py", line 43, in execute_send
server.login(args.email_name, args.email_passwd)
File "/usr/lib/python3.5/smtplib.py", line 693, in login
self.ehlo_or_helo_if_needed()
File "/usr/lib/python3.5/smtplib.py", line 599, in ehlo_or_helo_if_needed
if not (200 <= self.ehlo()[0] <= 299):
File "/usr/lib/python3.5/smtplib.py", line 439, in ehlo
self.putcmd(self.ehlo_msg, name or self.local_hostname)
File "/usr/lib/python3.5/smtplib.py", line 366, in putcmd
self.send(str)
File "/usr/lib/python3.5/smtplib.py", line 358, in send
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first

Python imaplib login failed

I'm working on mail application and encountering a big problem with Python imaplib.
Here is the code that I try to use to login to mail server.
M = imaplib.IMAP4(self.server,int(self.port))
M.login(self.user, self.password)
I'm using "port 143", "useSLL = false", no secure.
And here is the message that I receive when trying to login to server.
DEBUG:root:Login failed.
Traceback (most recent call last):
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 347, in getMail
M.login(self.user, self.password)
File "/opt/splunk/lib/python2.7/imaplib.py", line 520, in login
raise self.error(dat[-1])
error: Login failed.
None
Traceback (most recent call last):
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 724, in <module>
parseArgs()
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 716, in parseArgs
imapProc.getMail()
File "/opt/splunk/etc/apps/IMAPmailbox/bin/get_imap_email.py", line 352, in getMail
raise LoginError('Could not log into server: %s with password provided' % self.server)
__main__.LoginError: Could not log into server: (my server) with password provided
p/s: I have another mail application which get emails throw imap on ruby and it's working fine with port 143 no secure.
Anyone please help me to solve this problem. Thanks
Use this instead
M = imaplib.IMAP4_SSL(self.server,int(self.port))
M.login(self.user, self.password)
I am using imaplib.IMAP4_SSL instead of imaplib.IMAP4and this seems to work for me
I got a solution which work for both gmail and Outlook
def connect(self, username, password):
if self.tls:
self.server.starttls()
if(self.hostname == 'imap.outlook.com'):
imap_server = "outlook.office365.com"
self.server = self.transport(imap_server, self.port)
self.server = imaplib.IMAP4_SSL(imap_server)
(retcode, capabilities) = self.server.login(username,password)
self.server.select('inbox')
else:
typ, msg = self.server.login(username, password)
if self.folder:
self.server.select(self.folder)
else:
self.server.select()

Python Spam Email Sending Errors

import smtplib
fromaddr = "Insert your email here"
toaddr = ["insert receivers adress here"]
message = """From: fromname <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: Insert Subject here"""
emails_done = 1
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "InsertPassword")
for i in range(int(raw_input('how many emails?'))):
server.sendmail(fromaddr, toaddr,message)
print(emails_done)
emails_done = emails_done + 1
server.quit()
Im trying to spam my friend with 100 emails as a prank, but i have a few problems with the code, i get alot of different errors such as:
Traceback (most recent call last):
File "/Volumes/Data/Users/106299/Desktop/EMAIL .py", line 45, in <module>
server.sendmail(fromaddr, toaddr,message)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 723, in sendmail
self.rset()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 462, in rset
return self.docmd("rset")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 387, in docmd
return self.getreply()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 360, in getreply
+ str(e))
SMTPServerDisconnected: Connection unexpectedly closed: [Errno 54] Connection reset by peer
Ive Gotten up to 78 emails and it always ends there. Also sometimes it sends in one big email thread/change, rather then 100 separate emails.Here is another
Traceback (most recent call last):
File "/Volumes/Data/Users/106299/Desktop/EMAIL .py", line 45, in <module>
server.sendmail(fromaddr, toaddr,message)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 723, in sendmail
self.rset()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 462, in rset
return self.docmd("rset")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 387, in docmd
return self.getreply()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 363, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed
I am running python 2.7.8 on a MacBook Air
Any help would be appreciated :>
P.S sorry for crap formatting, first post.
A possibility is that gmail is rejecting requests after a certain number per second.
Try putting server.set_debuglevel(1) right after server.starttls(), this will let you see the debug details of the function call. This information will likely lead you to the solution.

What's causing this imaplib error in Python script for AppEngine?

This script:
import imaplib
user = "dave.trindall#gmail.com"
pwd = "***"
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("Inbox") # here you a can choose a mail box like INBOX instead
m.search("NEW")
makes this error for me:
Traceback (most recent call last):
File "c:\Program Files\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 701, in __call__
handler.get(*groups)
File "c:\Users\Dave\git_stuff\Touch Base\Touch Base\main.py", line 30, in get
m = imaplib.IMAP4_SSL("imap.gmail.com")
File "c:\Python26\lib\imaplib.py", line 1138, in __init__
IMAP4.__init__(self, host, port)
File "c:\Python26\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "c:\Python26\lib\imaplib.py", line 1149, in open
self.sock = socket.create_connection((host, port))
AttributeError: 'module' object has no attribute 'create_connection'
Why?
This fails because App-Engine disallows opening sockets in your application. See the 'Pure Python' section in http://code.google.com/appengine/docs/python/runtime.html, also discussion at http://groups.google.com/group/google-appengine/browse_thread/thread/4a8764d266ec17af
Note that while you can't make raw socket connections from App Engine, you can send mail using the Mail API and you can read a Gmail inbox using the Gmail Inbox Feed.

Erratic behavior with email attachments using python smtplib

My email script is based on this script at Fine Frog. I'm using this script to send HTML log files from a number of remote machines using a variety of ISPs.
The attachment isn't being sent consistently, however. It does work 80% of the time, but I'm getting two types of weird behavior. The first is where the email isn't sent at all, but throws the error(s) you see below
Traceback (most recent call last):
File "/root/sapapps/reporter/usage_report.py", line 336, in ?
se.send_mail(['thinkwelldesigns#g1234.com'], cd.contact, 'dave#1234.com', report_subject, text_body, files=[report_name], bcc=[cd.tech_email])
File "/usr/lib/python2.4/site-packages/sap/send_email.py", line 61, in send_mail
mail_server.sendmail(server_addr, addresses, message.as_string())
File "/usr/lib/python2.4/smtplib.py", line 692, in sendmail
(code,resp) = self.data(msg)
File "/usr/lib/python2.4/smtplib.py", line 489, in data
self.send(q)
File "/usr/lib/python2.4/smtplib.py", line 319, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected
Or, on some machines, this error is raised.
reply: '421 Command timeout, closing transmission channel\r\n'
reply: retcode (421); Msg: Command timeout, closing transmission channel
data: (421, 'Command timeout, closing transmission channel')
send: 'rset\r\n'
Traceback (most recent call last):
File "/root/sapapps/reporter/usage_report.py", line 336, in ?
se.send_mail(['thinkwelldesigns#1234.com'], cd.contact, 'dave#1234.com', report_subject, text_body, files=[report_name], bcc=[cd.tech_email])
File "/usr/lib/python2.4/site-packages/sap/send_email.py", line 61, in send_mail
mail_server.sendmail(server_addr, addresses, message.as_string())
File "/usr/lib/python2.4/smtplib.py", line 694, in sendmail
self.rset()
File "/usr/lib/python2.4/smtplib.py", line 449, in rset
return self.docmd("rset")
File "/usr/lib/python2.4/smtplib.py", line 374, in docmd
return self.getreply()
File "/usr/lib/python2.4/smtplib.py", line 348, in getreply
line = self.file.readline()
File "/usr/lib/python2.4/socket.py", line 340, in readline
data = self._sock.recv(self._rbufsize)
socket.error: (104, 'Connection reset by peer')
In the second instance of weird behavior, the email is processed without error, the attachment goes along, but some data is stripped out of the HTML attachment in the emailing process. IOW, if you login to the remote machine, you'll find the original file intact, but the attached file is missed log entries.
I'm guessing that these issues are unrelated problems, but does anyone have some advice on how to most reliably send HTML attachments?
TIA,
Dave
I had a problem before using smtplib.SMTP, and figured out the email server required using an SSL connection. You could try using smtplib.SMTP_SSL if the regular call fails.
The first problem which raised one of the two following errors:
smtplib.SMTPServerDisconnected: Server not connected
or
socket.error: (104, 'Connection reset by peer')
was solved by switching to Gmail as the mail server.
The second error where part of HTML attachment was stripped out was solved by closing the report file before the email script processed...
html_report.close()
I'm a Python newbie. :-|

Categories

Resources