Using pyramid_mailer results in ValueError: TPC in progress - python

I'm running pyramid on an Ubuntu Linux server, and am getting a ValueError when trying to use pyramid_mailer. My code is relatively simple, anything seems to cause it:
def my_view(request):
mailer = get_mailer(request)
emailMessage = Message(subject="Welcome", sender="noreply#mysite.com", recipients = ["me#email.com"], body="test")
mailer.send(emailMessage)
Results in this error:
Traceback (most recent call last):
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid-1.5-py2.7.egg/pyramid/router.py", line 242, in __call__
response = self.invoke_subrequest(request, use_tweens=True)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid-1.5-py2.7.egg/pyramid/router.py", line 217, in invoke_subrequest
response = handle_request(request)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid_debugtoolbar-2.0.2-py2.7.egg/pyramid_debugtoolbar/toolbar.py", line 160, in toolbar_tween
return handler(request)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid-1.5-py2.7.egg/pyramid/tweens.py", line 21, in excview_tween
response = handler(request)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid_tm-0.7-py2.7.egg/pyramid_tm/__init__.py", line 79, in tm_tween
manager.abort()
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/transaction-1.4.3-py2.7.egg/transaction/_manager.py", line 116, in abort
return self.get().abort()
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/transaction-1.4.3-py2.7.egg/transaction/_transaction.py", line 468, in abort
reraise(t, v, tb)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/transaction-1.4.3-py2.7.egg/transaction/_transaction.py", line 453, in abort
rm.abort(self)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/repoze.sendmail-4.2-py2.7.egg/repoze/sendmail/delivery.py", line 119, in abort
raise ValueError("TPC in progress")
ValueError: TPC in progress
I followed the instructions for "Getting Started (The Easier Way)" on this site: http://pyramid-mailer.readthedocs.org/en/latest/

This is a known issue. It can be worked around in the meantime by reverting to repoze.sendmail 4.1 (from 4.2)

recipients = ["me#email.com"]
here you can see
recipients – list of email addresses

This was the first error that I encountered while trying to set up an emailing system, through I cannot remember what I did. In any case, I finally got it working for a gmail sender for SMTP. Hope this someone else in my position:
import smtplib
sender = "noreply"
to = "username"
subject = "Verification Code"
headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to,
subject)
sEmailMessage = headers + "whatever message you want"
mailserver = smtplib.SMTP("smtp.gmail.com", 587)
#--- because of gmail
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
#---
mailserver.login("your_email_address#gmail.com", "your_password")
mailserver.sendmail("from_here#gmail.com", to_here#whatever.com, sEmailMessage)
mailserver.close()

Related

TypeError: object of type 'EmailMultiAlternatives' has no len()

Django app, sending an email using a script (using runscript), only on weekdays. Trying to use Google's STMP.
Here's the relavent script:
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labschedule.settings")
django.setup()
import datetime
from datetime import date
import smtplib
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
from labschedule import settings
def run():
today = date.today()
subject = "Daily Report for %s" % today
to = [settings.EMAIL_ADMIN]
from_email = 'blahblah#gmail.com' # My email
reservations = Event.objects.filter(day=today).order_by('cart')
last = Event.objects.latest('day')
if today >= today + datetime.timedelta(days=5):
countdown = last - datetime.timedelta(today)
warning = "Hey! You run out of open slots in %s days" % countdown
else:
warning = None
ctx = ({
'reservations' : reservations, 'warning' : warning, 'cart_choice' : cart_choice
})
html_content = render_to_string('schedule/email.html', ctx)
text_content = render_to_string('schedule/email.html', ctx)
msg = EmailMultiAlternatives(subject, text_content, to=to, from_email=from_email)
msg.attach_alternative(html_content, "text/html")
weekend = set([5, 6]) # Python week starts on Monday as 0
if today.weekday() not in weekend and settings.DAILY_EMAIL == True:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(settings.gmail_user, settings.gmail_password)
server.sendmail(from_email, to, msg)
server.close()
print ('Email sent!')
else:
pass
I went mostly of the tutorial here.
The error I receive:
TypeError: object of type 'EmailMultiAlternatives' has no len()
I'm newish, and I know it's something dumb, and would greatly appreciate any help.
EDIT: Traceback
Traceback (most recent call last):
File "/home/mrsaltz/labschedule/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_comm
and_line
utility.execute()
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django_extensions/management/email_notifications.py", line 63, in r
un_from_argv
super(EmailNotificationCommand, self).run_from_argv(argv)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django_extensions/management/email_notifications.py", line 75, in e
xecute
super(EmailNotificationCommand, self).execute(*args, **options)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django_extensions/management/utils.py", line 58, in inner
ret = func(self, *args, **kwargs)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django_extensions/management/commands/runscript.py", line 165, in h
andle
run_script(mod, *script_args)
File "/home/mrsaltz/.virtualenvs/scheduler/lib/python3.5/site-packages/django_extensions/management/commands/runscript.py", line 77, in ru
n_script
mod.run(*script_args)
File "/home/mrsaltz/labschedule/scripts/daily_email.py", line 40, in run
server.sendmail(from_email, to, msg)
File "/usr/lib/python3.5/smtplib.py", line 853, in sendmail
esmtp_opts.append("size=%d" % len(msg))
TypeError: object of type 'EmailMultiAlternatives' has no len()
SMTP_SSL.send() expects a bytestring not an instance of EmailMultiAlternatives
You shouldn't be mixing things here. EmailMultiAlternatives is a class from Django, but smtplib is from the Python standard library. EmailMultiAlternatives is supposed to be used with the Django mail library - which, in addition, takes care of all the SMTP connection and login logic.
All this is covered in the docs page you already linked to: you should follow that.
for argument of to (email) isn't filled as a single email, but it used for list of email/s. You should change:
msg = EmailMultiAlternatives(subject, text_content, to=to, from_email=from_email)
to
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
See this docs for more..

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.

Python application using office365 exchange server timing out

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

Error during sending mail

I try to send mail via python. I got a function:
def mail():
fromaddr = 'mymail#gmail.com'
toaddrs = 'targetmail#o2.pl'
msg = 'There was a terrible error that occured and I wanted you to know!'
# Credentials (if needed)
username = 'mymail#gmail.com'
password = 'password'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
When I try to execute this function it whows me WinError 10060. Error text below:
Traceback (most recent call last):
File "C:\python-factory\ServiceChecker\main\mainBlock.py", line 75, in <module> mail()
File "C:\python-factory\ServiceChecker\main\mainBlock.py", line 65, in mail server = smtplib.SMTP('smtp.gmail.com:587')
File "C:\Python34\Lib\smtplib.py", line 242, in __init__ (code, msg) = self.connect(host, port)
File "C:\Python34\Lib\smtplib.py", line 321, in connect self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python34\Lib\smtplib.py", line 292, in _get_socket self.source_address)
File "C:\Python34\Lib\socket.py", line 509, in create_connection raise err
File "C:\Python34\Lib\socket.py", line 500, in create_connection sock.connect(sa)
TimeoutError: [WinError 10060]
I don't know where is problem... i tried many mail servers (gmail,o2,wp,) all of them returned the same error. I tried also other available solutions in the internet to send mail via pyython.... the same problem...
Please help
According to your posted backtrace, you are failing at the line
server = smtplib.SMTP('smtp.gmail.com:587')
I've run that line and it works for me. The clue is in the TimeoutError. I believe you are having networking problems and the code itself is fine.
You do have an extra call to ehlo but as it stands you are not getting that far.
Additionally, it would probably be better to pass the port number as a separate argument, rather than using a colon to split it. E.g.
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
The documentation for smptlib is here: https://docs.python.org/2/library/smtplib.html
Try removing the second server.ehlo() . The one just before login. That worked for me.
toaddrs should be a list
toaddrs = ['targetmail#o2.pl']

Categories

Resources