want to send a email using smtplib but problem with recievers address - python-3.x

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')}

Related

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

smtplib, 'tuple' object has no attribute 'encode'

I am out of ideas how to solve this. I checked most smtplib threads and those about " AttributeError: 'tuple' object has no attribute 'encode'"
I am trying to create message template to send emails from Python3 script. For some reason, when I added message template I cannot fix that in any way.
import smtplib
import additional
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#server commends
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
#credentials of sender
FROM = "xxx.gmail.com"
PASSWORD = additional.x #hidden password in other .py file
#logging in
server.login(FROM, PASSWORD)
#template for recievers
TOADDR = ["reciever email"]
CC = ["FIRST CC", "2ND CC"]
SUBJECT = "testing"
TEXT = "Let's check if this works and I joined everything correctly"
#MSG template
FINAL_TO = CC + [TOADDR]
message = MIMEMultipart()
message['From'] = "Michal", FROM
message['To'] = TOADDR
message['Cc'] = ", ".join(CC)
message['Subject'] = SUBJECT
message.attach(MIMEText(TEXT))
MSG = message.as_string()
#Join reciever with CC
FINAL_TO = CC + [TOADDR]
server.sendmail(FROM, FINAL_TO, MSG)
TIME = datetime.datetime.now()
print("Email sent at {}".format(TIME))
As mentioned above, my output is :
Traceback (most recent call last):
File "/home/galander/Desktop/sending email/app.py", line 39, in <module>
MSG = message.as_string()
File "/usr/lib/python3.6/email/message.py", line 158, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python3.6/email/generator.py", line 116, in flatten
self._write(msg)
File "/usr/lib/python3.6/email/generator.py", line 195, in _write
self._write_headers(msg)
File "/usr/lib/python3.6/email/generator.py", line 222, in _write_headers
self.write(self.policy.fold(h, v))
File "/usr/lib/python3.6/email/_policybase.py", line 326, in fold
return self._fold(name, value, sanitize=True)
File "/usr/lib/python3.6/email/_policybase.py", line 369, in _fold
parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen))
AttributeError: 'tuple' object has no attribute 'encode'
Headers on a mime message must be strings. You have assigned a tuple to From, and a list to To.
Make those strings too:
message['From'] = "Michal <{}>".format(FROM)
message['To'] = ', '.join(TOADDR)

Python - Cannot Send Email

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.

Can Someone Please Tell Me What This Code Does

import imaplib,time
class Mail():
def __init__(self):
self.user= 'USERNAME'
self.password= 'PASSWORD'
self.M = imaplib.IMAP4_SSL('imap.gmail.com', '993')
self.M.login(self.user, self.password)
def checkMail(self):
self.M.select()
self.unRead = self.M.search(None, 'UnSeen')
return len(self.unRead[1][0].split())
email = Mail()
while 1:
print ('Sending')
time.sleep(2)
You initialize a class called Mail that supposedly uses the imaplib library to check the unread messages of a gmail account. However, after you assign email to an instance of Mail, your while loop, which is responsible for the action in your code, is comprised of two events; a print and a time.sleep().
So your code essentially is a long way of printing 'Sending' every 2 seconds.
Running after commenting out the line email = Mail() due to invalid credentials
bash-3.2$ python foo.py
Sending
Sending
^CTraceback (most recent call last):
File "foo.py", line 21, in <module>
time.sleep(2)
KeyboardInterrupt
bash-3.2$

Resources