I have a block of code which runs fine in my python application. When the celery worker runs this code, it fails to do so. Here is the code block:
def send_case_complete_email(owner_name, case_name, email):
try:
with open("utility/email/buildCompleteEmail.txt", 'rb') as email_file:
text = email_file.read().decode("utf-8")
text = text.replace("<owner>", owner_name).replace("<caseName>", case_name)
msg = MIMEText(text)
msg['Subject'] = "Case \'" + case_name + "\' is ready"
msg['From'] = config_access.app_configs['email']['from']
msg['To'] = email
server = smtplib.SMTP(config_access.app_configs['email']['host'])
if config_access.app_configs['email']['tls']:
server.starttls()
server.login(config_access.app_configs['email']['user'], config_access.app_configs['email']['password'])
server.sendmail(config_access.app_configs['email']['from'], email, msg.as_string())
print("Case completion email sent to " + email)
except Exception as e:
print(e)
With the error from the celery worker:
[2017-06-02 15:07:19,031: WARNING/PoolWorker-1] (500, b"5.3.3 Unrecognized command 'bm8ucmVwbHlAcGx1cmlsb2NrLmNvbQ==' [BN3PR03CA0080.namprd03.prod.outlook.com]")
Why would this happen?
The message you have posted is just a warning message. Are you sure the error here is from this piece of code. You can use logging here. Python Logging
Or if you are using Django then,Django Logging
. You can use logger.exception to get the full stacktrace. This shall tell you where exactly is the error coming from.
Related
I'm attempting to create a program that reads the unread emails and responds to the send with the usage of auto-reply which would be triggered by the use of certain phrases. I'm doing this in Mac OSX in Visual Code. I'm able to connect to IMAP and SMTP but then I get the following error,
smtplib.SMTPServerDisconnected: please run connect() first.
I tried to use an exception that was part of the smtplib which should be raised if the SMTP server disconnects, but it doesn't do anything.
def smtp_init():
print("Initializing STMP . . .",end = '')
global s
s = smtplib.SMTP(smtpserver,smtpserverport)
status_code = s.starttls()[0]
if status_code is not 220:
raise Exception('Starting tls failed: '+ str(status_code))
status_code = s.login(radr,pwd)[0]
if status_code is not 235:
raise Exception('SMTP login failed: '+ str(status_code))
print("Done. ")
except smtplib.SMTPServerDisconnected:
smtp_init()
continue
The expected results would be to have the program in a loop checking the emails and responding to them if they have a phrase that corresponds to the auto-reply.
I have an issue which I really cannot figure out.
The following snippets from my Python script zips a directory and sends a mail on success. It also sends a mail if an error occured. And here is the issue:
When I execute the script manually, everything works fine.
1 mail on success, 1 mail if an error occured.
If the script is run from cron though, I reveive over 50 emails if an error occures (on success only one)! All mails have the same content (the error message), and all mails are sent at the same time (exact as "hh:mm").
This is the script snippet:
def backup(pathMedia, pathZipMedia):
[...]
try:
createArchive(pathMedia, pathZipMedia)
except Exception as e:
sendMail('Error in zipping the media dir: ' + str(e))
sys.exit()
sendMail('Backup successfully created!')
def sendMail(msg):
sent = 0
SMTPserver = '[...]'
sender = '[...]'
destination = ['...']
USERNAME = '[...]'
PASSWORD = '[...]'
text_subtype = 'plain'
subject='Backup notification'
content=msg
try:
msg = MIMEText(content, text_subtype)
msg['Subject'] = subject
msg['From'] = sender
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
if (sent == 0):
conn.sendmail(sender, destination, msg.as_string())
sent = 1
finally:
conn.quit()
except Exception as e:
sys.exit()
My crontab is the following:
## run the backup script every 3 days at 4am
* 4 */3 * * /root/backup.py >/dev/null 2>&1
I fixed the orrucring errors now, but it still might happen again.
And I'm really curious about why this issue occurs!
Thanks!
The * at the beginning of your crontab line says "run this job every minute".
Presumably a successful run of the first job at 4:00 causes the following 59 runs to find that no work needs to be done, therefore they don't attempt to create a backup and they exit quietly without sending email. But an unsuccessful run at 4:00 will leave work to be done by the next job at 4:01, and again the minute after that, and so on until 4:59. All of those jobs try to create a backup and all of them fail, so you get something like 60 failure emails. (Or fewer if one of the jobs manages to succeed, breaking the chain of failures.)
To fix the crontab line to run the job only one time at 4:00am, change the first * to a 0.
I don't know why your failure emails all have the same timestamp. Are you certain that they're all exactly the same? If so, perhaps they're being batched by your mail system and are assigned a Date header at the time the batch is processed. Or perhaps all of the jobs are started by cron and then they all wait, blocked until some system timeout or other event occurs, and then they all experience the failure simultaneously and all send emails at the same time.
Been having an issue with this code:
from telnetlib import Telnet
class doTelnet:
def login(self):
# Configure login variables for input
self.user = self.user.encode('ascii') + b'\n'
self.password = self.password.encode('ascii') + b'\n'
self.terminal_type = self.terminal_type.encode('ascii') + b'\n'
# Do login
# TODO Add functionality for user control of expected login prompt (some servers send 'Username: ', I'm sure theres other options)
self.telnet.read_until('login: ')
self.telnet.write(self.user)
self.telnet.read_until('Password: ')
try:
self.telnet.write(self.password)
print('[*]\tSuccessfully authenticated to {0}:{1}'.format(self.host, self.port))
self.login_status = 1
except Exception as self.e:
print('[!]\tError authenticating to {0}:{1}\n{2}'.format(self.host, self.port, self.e)
# Set terminal type
self.telnet.write(self.terminal_type)
It consistently fails on the "self.telnet.write" section, which I can't understand why that might be. Anyone a wizard?
File "C:\Users\user\Downloads\CiscoIOSSNMPToolkit\doTelnet.py", line 45
self.telnet.write(self.terminal_type)
^
SyntaxError: invalid syntax
Is the error.
https://github.com/GarnetSunset/CiscoIOSSNMPToolkit/blob/master/doTelnet.py
You are missing a parenthesis at the end of your print statement in the exception block which is why you are throwing your current syntax error.
i have a couple issues with sending Email with Python using my own SMTP/IMAP Server.
Here's the code :
import sys
import imaplib
import smtplib
import email
import email.header
import datetime
smtp_session = smtplib.SMTP(mail_server)
try:
smtp_session.ehlo()
except :
err = sys.exc_info()[0]
message = """\
From: %s
To: %s
Subject: %s
%s""" % (email_from, ", ".join([email_to]), "subject", "body")
try:
smtp_session.sendmail(email_from, [email_to], message)
smtp_session.quit()
except:
err = sys.exc_info()[0]
if err != "" or err !=None:
NagiosCode = 2
NagiosMsg = "CRITICAL: Script execution failed : " + str(err)
Ok so for the two issues i have:
When i send a mail from my script i need the mail to appear in the "sent items" diretory of my mail box who send it.
Second issue i have : When sending my mail i catch this exception :
<class 'smtplib.SMTPException'>
EDIT : Exception trace :
File "checkIMAP_client.py", line 153, in <module>
smtp_session.login(login, password)
File "/usr/lib64/python2.6/smtplib.py", line 559, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
EDIT :
It seems my SMTP server doesn't require authentification.
But the program still returns me an empty exception.
Code is updated.
So for the two issues i had, i found the answers thanks to the above comments :
Putting my sent e-mail via SMTP in the right mailbox in the Sent directory :
https://pymotw.com/2/imaplib/
Look for "Uploading messages"
Exception issue :
I had no auth methods set on my SMTP server.
I'm getting this error:
raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused:
{'example#hotmail.com': (550, '5.1.1 : Recipient
address rejected: hotmail.com')}
when trying to run my python script.
Regardless of what recipient address I put in, it will still give me the same error. I have postfix's configuration installed as local and it properly recognizes 'localhost' but not any of the sender addresses. This is my code:
import smtplib
def sendEmail(addressFrom, addressTo, msg):
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(addressFrom, addressTo, msg)
server.quit()
msg = "This is the content of the email"
addressFrom = ""
addressTo = "example#hotmail.com"
sendEmail(addressFrom, addressTo, msg)
And this is the main.cf file for postfix. Looking at it now,mydestination is only set to local addresses, could that be the issue?
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific: Specifying a file name will cause the first
# line of that file to be used as the name. The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
myhostname = user-desktop
**mydomain = hotmail.com**
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
**mydestination = user-desktop, localhost.$mydomain www.$mydomain**
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = loopback-only
default_transport = error
relay_transport = error
inet_protocols = ipv4
Thank you in advance
I faced a similar issue in my python script.
Use the following command to change the configuration of Postfix to Internet Site
sudo dpkg-reconfigure postfix
Change the Postfix configuration to Internet Site. This will resolve your problem and can send mail to any mail address.
Your code looks OK. This is very likely a configuration issue with Postfix.
Hi I had a similar problem. I was getting the error:
(550, '5.7.1 Client does not have permissions to send as this sender')
Turning on TLS, adding the ehlo commands explicitly fixed the problem for me. Hope it helps.
def mail(msg):
email_server = "mail.some-server.com"
sender = "me#some-server.com"
to = "you#some-server.com"
subject = "How about those Mariners!"
headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)
text = msg
message = headers + text
mailServer = smtplib.SMTP(email_server)
mailServer.set_debuglevel(1)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login('user', 'pass')
mailServer.ehlo()
mailServer.sendmail(sender, to, message)
mailServer.quit()