I been trying to make a python program that sends email but i keep getting this error
Traceback (most recent call last):
File "C:\Users\25194\PycharmProjects\Gmail\Yo.py", line 25, in <module>
smtp.sendmail(email_sender, email_password, em.as_string())
File "C:\Users\25194\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 901, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'google login': (553, b'5.1.3 The recipient address <Gmail app password> is not a valid RFC-5321\n5.1.3 address. Learn more at\n5.1.3 https://support.google.com/mail/answer/6596 k9-20020a7bc409000000b003c6bd91caa5sm17184983wmi.17 - gsmtp')}
The code is
from email.message import EmailMessage
import ssl
import smtplib
email_sender = 'oropyt32#gmail.com'
email_password = 'google login'
email_reciver = 'milkiwasihunpro#gmail.com'
subject = 'Check mate'
body = """
I am making this sending this isnt it cool oro
"""
em = EmailMessage()
em['From'] = email_sender
em['TO'] = email_reciver
em['Subject'] = subject
em.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
smtp.login(email_sender, email_password)
smtp.sendmail(email_sender, email_password, em.as_string())
i am having hard time figuring out how to fix it
... b'5.1.3 The recipient address is not a valid RFC-5321\n5.1.3 address. ...
Obviously you are using a password in place where an email is expected
smtp.sendmail(email_sender, email_password, em.as_string())
From the documentation of sendmail:
SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())
So you give the email_password where to_addrs is expected. No wonder that it complains about your password used as recipient. You probably meant to use email_reciver instead.
Related
I tried following a youtube video on how to use smtplib to send emails, however whenever I try to send anything it gives me this error.
in alert_mail
msg.set_content(body)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/email/message.py", line 1162, in set_content
super().set_content(*args, **kw)
TypeError: super(type, obj): obj must be an instance or subtype of type
I really don't know why as I followed the video very closely, only changing the Gmail credentials and passwords to my own test accounts.
import smtplib
from email.message import EmailMessage
def alert_mail(subject, body, to):
msg = EmailMessage
msg.set_content(body)
msg["subject"] = subject
msg["to"] = to
user = "helios.alert.system#gmail.com"
msg["from"] = user
password = #2 way encription password would be here, but thats not the issue
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(user,password)
server.send_message(msg)
server.quit()
alert_mail("Hey","Hey this is my first com method" , "helios.alert.system#gmail.com") # sends email to itself, doesn't work even when some different address is entred
Any advice will be appreciated!
The video: https://www.youtube.com/watch?v=B1IsCbXp0uE
You should add an opening and closing parenthesis to the msg = EmailMessage line, remember that EmailMessage is an object, so you must use the correct syntax for creating one. This code below should work:
server = smtplib.SMTP(GMAIL_SERVER, GMAIL_PORT)
server.starttls()
server.login(EMAIL_SOURCE, PWD_SOURCE)
msg = EmailMessage()
msg['From'] = EMAIL_SOURCE
msg['To'] = TO_EMAIL
msg['Subject'] = YOUR_SUBJECT
msg.set_content(bodyOfMail)
server.send_message(msg)
del msg
server.quit()
How do I use the Python SoftLayer client (using v5.7.1) to determine the location (eg: dal10) for an NFS billing item (endurance storage)?
I used some other examples here on SO and came up with this, but the call failed:
objectFilter = {"billingItem": {"id": {"operation": "12345"}}}
account.getAllBillingItems(filter=objectFilter)
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/SoftLayer/transports.py", line 240, in __call__
raise _es(ex.faultCode, ex.faultString)
SoftLayer.exceptions.SoftLayerAPIError: SoftLayerAPIError(SOAP-ENV:Server): Internal Error
Try using the following python script to get the billing item detail and the location too.
import json
import SoftLayer
API_USERNAME = 'set me'
API_KEY = 'set me'
client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY)
billingItemId = 1234
mask = "mask[location]"
try:
response = client['SoftLayer_Billing_Item'].getObject(mask=mask, id=billingItemId)
print(response)
except SoftLayer.SoftLayerAPIError as e:
"""
If there was an error returned from the SoftLayer API then bomb out with the
error message.
"""
print("Unable to retrieve the billing item information. "
% (e.faultCode, e.faultString))
I am able to send mail without issue when I implement the same code very plain without using any functions. But when I try to send mail using a function I am getting mail as my senders account is disabled and it is blocking my mail and account.
Have to implement a code for sending mails after certain filters are met in a function so that it can be used to send mail whenever wanted.
My code snippet:
import smtplib
def setup_mail():
global smtpObj,sender,receivers,message
sender = 'sample#gmail.com'
receivers = ['sample1#gmail.com','sample2#gmail.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: 1 MIN candle 15 points alert
TIME: watch out next 2 minutes
"""
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("sample#gmail.com","samplepassword")
setup_mail()
def sending_mails(smtpObj):
smtpObj.sendmail(sender, receivers, message)
for i in range(3):
sending_mails(smtpObj);
print("Successfully sent email")
The error i got,
Traceback (most recent call last): File "C:/Users/Arun/PycharmProjects/Astro/venv/Scripts/ZERODHA_DEV/sendmail.py", line 22, in sending_mails(smtpObj); File "C:/Users/Arun/PycharmProjects/Astro/venv/Scripts/ZERODHA_DEV/sendmail.py", line 20, in sending_mails smtpObj.sendmail(sender, receivers, message) File "C:\Python\lib\smtplib.py", line 888, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (451, b'4.3.0 Mail server temporarily rejected message. s77sm14888153pfc.164 - gsmtp')
However it works with a simple code like,
import smtplib
global smtpObj,sender,receivers,message
sender = 'sample#gmail.com'
receivers = ['sample1#gmail.com','sample2#gmail.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: 1 MIN candle 15 points alert
TIME: watch out next 2 minutes
"""
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtpObj.login("sample#gmail.com","samplepassword")
for i in range(3):
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
The immediate problem is that your message is indented; a valid SMTP message contains two literal adjacent newlines to demarcate the headers from the body.
While you can assemble simple email messages from ASCII strings, this is not tenable for real-world modern email messages. You really want to use the email library (or a higher level third-party wrapper or replacement) to handle all the corner cases of email message encapsulation, especially if you are not an expert on email and MIME yourself.
I'm following a class online and I'm doing as the instructor does. They used a with block for this bit of code to send the email, but it gives me an SyntaxError. I don't understand what I'm doing wrong here, I followed the exact same steps.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
#Replaced email, name, & password w/ filler
message = MIMEMultipart()
message["from"] = "First_Name Last_Name"
message["to"] = "email#email.com"
message["subject"] = "This is a test"
message.attach(MIMEText("Body")
with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login("email#email.com", "password1234")
smtp.send_message(message)
print("Sent...")
Here's the error I get:
File "c:\Users\Mofongo\Google Drive\HelloWorld\app.py", line 11
with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp:
^
SyntaxError: invalid syntax
You are missing a closing parenthesis in the message.attach(MIMEText("Body")).
I'm doing an exercise on writing a module in python 3.8 idle (Mac) to send emails from my gmail account. It is giving me the error:
smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first.
THE COMPLETE RUNNING RESULT:
= RESTART: /Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py
person_name
Thank you for sharing!
Traceback (most recent call last):
File "/Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py", line 58, in <module>
main()
File "/Users/mimikatz/Desktop/python/Python_note&exercise/send_email_gmail.py", line 51, in main
s.send_message(msg)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 970, in send_message
return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 871, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (503, b'5.5.1 EHLO/HELO first. c18sm12642612wmk.18 - gsmtp', 'xxxxx#gmail.com')
The first two lines (person_name Thank you for sharing!) are from the 'message.txt' file.
MY CODE IS:
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_addr = 'xxxxxg#gmail.com'
password = 'xxxxxxxxxxx'
smtp_server = 'smtp.gmail.com'
def get_contacts(self):
names = []
emails = []
with open(self, '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(self):
with open(self, '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_SSL(smtp_server)
s.ehlo()
s.connect(smtp_server,465)
s.login(from_addr, 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'] = from_addr
msg['To'] = email
msg['Subject'] = 'This is TEST'
# add in the message body
msg.attach(MIMEText(message, 'plain', 'utf-8'))
# 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()
I saw this code in one of the questions asked here and it looked great to me as an example, so I wanted to try it out. But my problem turns out different than what the original one had. From the running result, it looks like the """print(message)""" command is successfully loaded. The problem occurs at """s.send_message(msg)""". I checked online several similar cases but couldn't find answer that suits this condition.
Really grateful to any help :)
Acorus
Problem solved thanks to Konrad
Swapping the .ehlo() with .connect()
& Changing the password to an authentication code generated from gmail setting 2-step verification app password. I used "mail" & "mac" to generate the verification code.
While I have never used Python to send emails, I've spent some time communicating with SMTP servers via Telnet.
You need to connect to the server first, then send EHLO, then authenticate and finally send the message. Your code seems to try sending EHLO before connecting to the server.
Try swapping those two lines.