Python - Cannot Send Email - python-3.x

I am running Python 3.4.2, on Windows 7 Enterprise, 64 bit.
I have the below script (write_email.py) that receives an error when run:
# smtplib module send mail
import smtplib
TO = 'address#somedomain.com'
SUBJECT = 'TEST MAIL'
TEXT = 'Here is a message from python.'
# Gmail Sign In
gmail_sender = 'address#gmail.com'
gmail_passwd = '' #this is left blank on purpose
server = smtplib.SMTP('smtp-relay.gmail.com', 25)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join(['To: %s' % TO,
'From: %s' % gmail_sender,
'Subject: %s' % SUBJECT,
'', TEXT])
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('email sent')
except:
print ('error sending mail')
server.quit()
The error is:
Traceback (most recent call last):
File "email_test.py", line 17, in <module>
server.login(gmail_sender, gmail_passwd)
File "C:\Python34\lib\smtplib.py", line 652, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (501, b'5.5.2 Cannot Decode response 13sm147030
88ith.4 - gsmtp')
I've done a lot of searching to resolve this, but so far no luck.

Related

Python script for Parsing Office 365 HTML email and getting body

This is script to read email and parse body from outlook 365. For me does not work.
I have outlook 365 account without TFA. TFA is not activated
what could be a problem?
#!/usr/bin/python3
from email.message import EmailMessage
import email
import imaplib
import re
import sys
import logging
import base64
import email.parser
import html2text
import requests
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-mpass', '-mailbox_password', dest = 'mailbox_password', help = 'mailbox password.')
args = parser.parse_args()
user = 'someuser#company.com'
mailbox_password ='Email Password' #args.mailbox_password
def get_email_body(body):
if body.is_multipart():
for payload in body.get_payload():
print('To:\t\t', body['To'])
print('From:\t', body['From'])
print('Subject:', body['Subject'])
print('Date:\t',body['Date'])
for part in body.walk():
if (part.get_content_type() == 'text/plain') and (part.get('Content-Disposition') is None):
output = part.get_payload()
else:
print('To:\t\t', body['To'])
print('From:\t', body['From'])
print('Subject:', body['Subject'])
print('Date:\t', body['Date'])
print('Thread-Index:\t', body['Thread-Index'])
text = f"{body.get_payload(decode=True)}"
html = text.replace("b'", "")
h = html2text.HTML2Text()
h.ignore_links = True
output = (h.handle(f'''{html}''').replace("\\r\\n", ""))
output = output.replace("'", "")
# output in one line
#output = output.replace('\n'," ")
output = output.replace('*', "")
return output
def clear_inbox(conn, dest_folder):
output=[]
result = conn.uid('COPY', emailid, dest_folder)
output.append(result)
if result[0] == 'OK':
result = mov, data = conn.uid('STORE',emailid, '+FLAGS', '(\Deleted Items)')
conn.expunge()
conn = imaplib.IMAP4_SSL("outlook.office365.com")
conn.login(user,mailbox_password)
conn.select("Inbox")
try:
resp, items = conn.uid("search",None, 'All')
items = items[0].split()
for emailid in items:
resp, data = conn.uid("fetch",emailid, "(RFC822)")
if resp == 'OK':
email_body = data[0][1].decode('utf-8')
email_message = email.message_from_string(email_body)
subject = email_message["Subject"]
if subject.lower().startswith('Darktrace'.lower()):
output = get_email_body(email_message)
#do some task
# move emails to Processed folder and clear Inbox
clear_inbox(conn, "Processed")
else:
clear_inbox(conn, "backup")
except IndexError:
print("No new email")
conn.close()
conn.logout()
This is error:
Traceback (most recent call last):
File "d:\python\lib\imaplib.py", line 1047, in _command_complete
typ, data = self._get_tagged_response(tag, expect_bye=logout)
File "d:\python\lib\imaplib.py", line 1173, in _get_tagged_response
self._get_response()
File "d:\python\lib\imaplib.py", line 1075, in _get_response
resp = self._get_line()
File "d:\python\lib\imaplib.py", line 1185, in _get_line
raise self.abort('socket error: EOF')
abort: socket error: EOF
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Dev Codes\ReadOutlookEmail.py", line 74, in
resp, data = conn.uid("fetch", emailid, "(RFC822)")
File "d:\python\lib\imaplib.py", line 890, in uid
typ, dat = self._simple_command(name, command, *args)
File "d:\python\lib\imaplib.py", line 1230, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "d:\python\lib\imaplib.py", line 1049, in _command_complete
raise self.abort('command: %s => %s' % (name, val))
abort: command: UID => socket error: EOF

Python Django LineBot Error 54 'Connection reset by peer'

I'm trying to crete linebot through python Django, I want to send some messages and let it scrape the website. Since there is form on the website, I use post request to send the form.
Although I scrape the data successfully, there is error message showed in the python. It seems linebot occupy post method in Django and I send another post request again. I'm not sure my understanding is correct. I can't find any solution about this. Could someone teach me how to fix it?
Exception happened during processing of request from ('127.0.0.1', 50246)
Traceback (most recent call last):
File "/usr/local/anaconda3/lib/python3.8/socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "/usr/local/anaconda3/lib/python3.8/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/local/anaconda3/lib/python3.8/socketserver.py", line 720, in __init__
self.handle()
File "/usr/local/anaconda3/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle
self.handle_one_request()
File "/usr/local/anaconda3/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/usr/local/anaconda3/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer
Below is my code, I receive some keyword and post request to website. Finally, reply to user
#csrf_exempt
def callback(request):
if request.method == 'POST':
signature = request.META['HTTP_X_LINE_SIGNATURE']
body = request.body.decode('utf-8')
content = "None"
try:
events = parser.parse(body, signature)
except InvalidSignatureError:
return HttpResponseForbidden()
except LineBotApiError:
return HttpResponseBadRequest()
for event in events:
if isinstance(event, MessageEvent):
msg = event.message.text.strip()
if msg.startswith('!'):
msg = msg.replace('!', '')
if msg == 'temp':
content = "HELP"
elif msg.startswith(' '):
content = 'Command not found'
elif ' ' in msg:
info = msg.split(' ')
if len(info) > 2:
content = 'Too many arguments'
else:
ID = info[1]
temp = temperature.TempReport(ID)
content = temp.scrape()
#content = 'Test'
else:
content = 'Unknown command'
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=content)
)
print('submit success')
else:
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=msg)
)
return HttpResponse()
else:
return HttpResponseBadRequest()
Here is scrape code
def scrape(self):
if not self.postToServer():
return f'ID:{self.ID} submit temperature fail!'
return f'ID:{self.ID} submit temperature successfully
def postToServer(self):
self.session.post(self.url_in, data=self.payload)
sleep(0.1)
resp = self.session.get(self.url_out)
sleep(0.1)
soup = BeautifulSoup(resp.text, features='lxml')
result = soup.find(class_='title-text').text.strip()
return 0 if not 'completed' in result else
The post request work fine and the error happened when I return HttpResponse in callback function. I don't know what is the issue here...

want to send a email using smtplib but problem with recievers address

i have created a tkinter form in which user is asked to enter his email and when the asked details are submitted i want to send OTP to the address entered by user,but i am running into error which is reciever address is not valid(i guess).below,i am giving the code that shall be essential
'''
emailstring = tk.StringVar(root)
email = tk.Label(root, text="E-mail").grid(row=2)
email_entry = tk.Entry(root, textvariable=emailstring).grid(row=2, column=1)
receiver_mail =emailstring.get()
root.mainloop()
sender_mail = "godsownprogrammer#gmail.com"
message = "This is a test program\nYou are Trying to register your Email\nYour otp is :%s", otp_generator()
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("godsownprogrammer", "xxxxx")
s.sendmail(sender_mail, receiver_mail, message)'''
i have trimmed non essential parts
now here is the error
Traceback (most recent call last):
File "C:/Users/91970/PycharmProjects/pythonProject/tk_new/main.py", line 63, in <module>
s.sendmail(sender_mail, receiver_mail, message)
File "D:\python 3.7\lib\smtplib.py", line 881, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'': (555, b'5.5.2 Syntax error. n24sm4653515pgl.27 - gsmtp')}

How to work around problem with Python smtpd?

I want to make a small SMTP server for testing, using Python, so I was trying the server example code
https://pymotw.com/2/smtpd/
import smtpd
import asyncore
class CustomSMTPServer(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print 'Receiving message from:', peer
print 'Message addressed from:', mailfrom
print 'Message addressed to :', rcpttos
print 'Message length :', len(data)
return
server = CustomSMTPServer(('127.0.0.1', 1025), None)
asyncore.loop()
Together with the example client code on that same page:
import smtplib
import email.utils
from email.mime.text import MIMEText
# Create the message
msg = MIMEText('This is the body of the message.')
msg['To'] = email.utils.formataddr(('Recipient', 'recipient#example.com'))
msg['From'] = email.utils.formataddr(('Author', 'author#example.com'))
msg['Subject'] = 'Simple test message'
server = smtplib.SMTP('127.0.0.1', 1025)
server.set_debuglevel(True) # show communication with the server
try:
server.sendmail('author#example.com', ['recipient#example.com'], msg.as_string())
finally:
server.quit()
However, when I try to run the client, I am getting the following on the server side:
error: uncaptured python exception, closing channel <smtpd.SMTPChannel connected 127.0.0.1:38634 at 0x7fe28a901490> (<class 'TypeError'>:process_message() got an unexpected keyword argument 'mail_options' [/root/Python-3.8.1/Lib/asyncore.py|read|83] [/root/Python-3.8.1/Lib/asyncore.py|handle_read_event|420] [/root/Python-3.8.1/Lib/asynchat.py|handle_read|171] [/root/Python-3.8.1/Lib/smtpd.py|found_terminator|386])
^CTraceback (most recent call last):
File "./mysmtpd.py", line 18, in <module>
asyncore.loop()
File "/root/Python-3.8.1/Lib/asyncore.py", line 203, in loop
poll_fun(timeout, map)
File "/root/Python-3.8.1/Lib/asyncore.py", line 144, in poll
r, w, e = select.select(r, w, e, timeout)
KeyboardInterrupt
Then I found this Issue page:
https://bugs.python.org/issue35837
and I think that that is the problem I've been running into.
That issue hasn't been fixed yet, so I was wondering if, meantime, is there something that I can modify in the example client code that would get around the problem that is described in that issue?
Thanks,
Jim
Add an mail_options=None in your process_message() function.
Just for reference, do the same with the rcpt_options argument.
Ref: https://docs.python.org/3/library/smtpd.html?highlight=process_message#smtpd.SMTPServer.process_message
The error seems to appear
in the line with def process_message(self, peer, mailfrom, rcpttos, data):.
You can replace it with def process_message(self, peer, mailfrom, rcpttos, data,**my_krargs):

Python3 SMTP 'Connection unexpectedly closed'

Could somebody please tell me why I am getting a SMTPServerDisconnected("Connection unexpectedly closed") error from the following code?
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
MY_ADDRESS = '---'
PASSWORD = '---'
def get_contacts(filename):
"""
Return two lists names, emails containing names and email
addresses
read from a file specified by filename.
"""
names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0])
emails.append(a_contact.split()[1])
return names, emails
def read_template(filename):
"""
Returns a Template object comprising the contents of the
file specified by filename.
"""
with open(filename, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
def main():
names, emails = get_contacts('contacts.txt') # read contacts
message_template = read_template('message.txt')
# set up the SMTP server
s = smtplib.SMTP('smtp.gmail.com', 465)
s.ehlo()
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
# For each contact, send the email:
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message =
message_template.substitute(PERSON_NAME=name.title())
# Prints out the message body for our sake
print(message)
# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email
msg['Subject']="This is TEST"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
if __name__ == '__main__':
main()
Obviously when I run the code my address and password is filled in.
The traceback I get from this when running in terminal is:
Traceback (most recent call last):
File "emailAlert2.py", line 71, in
main()
File "emailAlert2.py", line 40, in main
s = smtplib.SMTP('smtp.gmail.com', 465)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 251, in init
(code, msg) = self.connect(host, port)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Thanks
The Google Gmail server is hanging up on your (dropping your connection attempt).
Provided that you have enabled third party access (link) to your Gmail account, change your code as follows:
s = smtplib.SMTP('smtp.gmail.com', 465)
s.ehlo()
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
Change to this:
s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
s.ehlo()
s.login(MY_ADDRESS, PASSWORD)
The reason for the hang up is that you are creating a connection using an unencrypted method (smtplib.SMTP()). Google is expecting that you are connecting using SMTPS which requires SSL.
Try port number 587 instead of port 465 in s = smtplib.SMTP('smtp.gmail.com', 465)
Probably you may need to come up with App password instead of your default password - Check this out - https://support.google.com/accounts/answer/185833

Resources