smtp error 534 connecting to gmail python3 - python

I've seen a lot of other posts with the same issue, I tried all of the following:
allow access to less secure app on gmail
Unlock token on google
make an app specific password
allow IMAP on gmail
Nothing is working, i still get the same error message:
SMTPAuthenticationError: (534, b'5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/?p=WebLoginRequired s3sm5978501edm.78 - gsmtp')
This is my code on my python jupiter notebook:
sender_email = "xxx#gmail.com"
receiver_email = "yyy#gmail.com"
password = "xxxxxx"
message = MIMEMultipart("alternative")
message["Subject"] = "new properties for rent"
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = "Hi, new properties satisfy your search on daft: %s" % dictionary
html = "<html><body>%s</body></html>" % emailBody
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.ehlo()
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)

There's a couple of reasons for this.
But since you exhausted most of them, and after talking in the comments. It's clear that you were sitting behind some sort of VPN or shared internet connection.
Some times, logging in on your account in a browser from this VPN/Shared connection would solve the problem. If not, the fastest and easiest way around this is to swap to a single-user connection (home wifi, dedicated VPS, something where only a handful of users might be sitting).
Common issues are: You're using Tor, a popular VPN provider, a school/company network.
Here's more information on the topic:
https://support.google.com/websearch/answer/86640?hl=en

Related

smtplib.SMTPConnectError: (421, b'Service not available') while using my pycharm to send a mail with python

i got the above error each time i try sending a mail using python. am somewhat new to this whole smtp thing. below is my code. please help.
import smtplib
my_email ="okoyekennethoptimizer#gmail.com"
password = "nmmrjdphptwfgjgb"
connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs="okoyek10#yahoomail.com", msg="hello")
connection.close()
please help. its been giving me tough time
Try creating an "App password" after enabling 2-step auth in your Gmail. You still need to do some lookup but generally, this should help.
The trick is in:
Enabling less secure apps.
Make sure your account has 2FA.
Generating an app password under My Google Account>>Security under Signing in to Google.
Replace the 16-digit password with the password you've placed in the password variable.
Just before connection.starttls() add connection.ehlo().
A code for example:
my_email ="okoyekennethoptimizer#gmail.com"
app_password = "16-digit-app-password"
connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.ehlo()
connection.starttls()
connection.login(user=my_email, password=app_password)
Also you SHOULD create From:, To:, and Subject: message headers, separated from the message body by a blank line.
E.g.
msg = "\r\n".join([
"From: user_me#gmail.com",
"To: user_you#gmail.com",
"Subject: Any subject",
"",
"Good Evening, how are you?"
])

How to use SMTP with Apple iCloud Custom Domain

I would like to use Python's SMTP to send automated emails with a custom domain iCloud+ email address. However, I can't get logged into the SMTP servers. I will always either get "Mailbox does not exist" or "Authentication failed".
From the Apple support pages it seems like you need to use SSL over port 587. Additionally, they want you to generate an "app-specific password" for outside applications. This led me to the following code:
import smtplib, ssl
smtp_server = "smtp.mail.me.com"
port = 587 # For SSL
# Create a secure SSL context
context = ssl.create_default_context()
sender_email = "me#example.com" # Enter your address
receiver_email = "you#example.com" # Enter receiver address
password = "some,password" # app specific password from Apple ID settings
message = """\
To: {to}
From: {sender}
Subject: Hello There
This was sent through Python!
""".format(to=receiver_email, sender=sender_email)
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
# Send email here
server.sendmail(sender_email, receiver_email, message)
However, this was still giving me a connection error. Only when I changed the last part to use TLS instead would it connect and give me an authentication error. This was taken from this question: SMTP_SSL SSLError: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:590)
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.ehlo() # Can be omitted
server.login(sender_email, password)
# Send email here
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
import traceback
print(traceback.format_exc())
finally:
server.quit()
So how can I use my custom domain address with Apple's iCloud+ service with Python's SMTP?
Just before I was going to ask this question, I solved it!
After reading this reddit post, I figured that all custom domain iCloud+ accounts are actually alias of some sort to the main iCloud account. So, I tried logging into my "main" iCloud account. This worked with the above code and sent the email! However, the from was still not my custom domain email address.
This is a somewhat easy fix though, simply modify the "From: <sender>" line in the email body. I'm not sure if this should be done (since it's technicaly faking who you are) but it seems to work. If any email experts know of better ways to do this please comment/answer though! The following code is what I used:
sender_email = "me#icloud.com" # this is who we actually are
sender = "me#example.com" # this is who we appear to be (i.e. custom domain email)
receiver_email = "you#example.com" # this is to who we have sent the email
message = """\
To: {to}
From: {sender}
Subject: Hello There
This was sent through Python!
""".format(to=receiver_email, sender=sender) # this is what changed, we use an alias instead
# ...
server.sendmail(sender_email, receiver_email, message)

HTML Email doesn't send (python3)

I'm trying to send an HTML email, however, when I run this code, literally nothing happens. I sit and wait as the program never finishes. What did I do wrong?
import smtplib, ssl, getpass
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "REDACTED"
receiver_email = "REDACTED"
password = getpass.getpass()
html = """
<html>
<head></head>
<body>
<h1>HEADER</h1>
<br>
body<br>
</body>
</html>
"""
msg = MIMEMultipart()
attach = MIMEText(html, 'html')
msg.attach(attach)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg)
server.close()
The msg needs to be flattened to a string before passing it to the sendmail method:
server.sendmail(sender_email, receiver_email, str(msg))
Also, you'll probably want to set some headers on the msg object:
msg.add_header('From', sender_email)
msg.add_header('Subject', 'whatever')
Enabling the debug output for the SMTP object would help to track down these problems, try inserting this line above the server.login call:
server.set_debuglevel(1)
If you're going to be working with email though it may be worth looking in to the email.message.EmailMessage class.
I've found sending mail using gmails SMTP server hard and difficult to work out (The only way I have even gotten it to work is by using a temporary thing that lets me send emails through my email address and only works half the time)
Instead, I suggest sending your email through SendGrid, using their python API, or another service that offers a similar function (Not being biased just have used SendGrid before and found it very easy and reliable) and just send a request to that every time you want to send an email.
I know its a dodgy way to get it to work but its the only way I've been able to send emails through my Gmail account using python :)
(Id comment this as it isn't really an answer but a workaround however I don't have enough reputation)

How can I send e-mails from python without having to enable less secure apps?

I am having trouble sending an e-mail without having to enable google's less secure apps: https://myaccount.google.com/lesssecureapps . How can I modify the code in Python so that I can send e-mail without having to enable this? I need to disable this option, because I am building an application in which the user can send a feedback e-mail to the developer, so I cannot force the user to enable less secure apps.
My code in Python:
def send_email(self):
print("send e-mail to developer")
sender_email = self.email.text
sender_password = self.password.text
sender_feedback = self.feedback_message.text
print("email is: ", type(sender_email))
print("pass is: ", sender_password)
print("feedback message is: ", sender_feedback)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls() # encrypt connection
server.login(sender_email, sender_password)
subject = 'Feedback'
msg = sender_feedback
msg = f"Subject: {subject} \n\n {msg}"
server.sendmail(
# from,to,message
sender_email,
'my_email#gmail.com',
msg
)
print("E-MAIL HAS BEEN SENT!")
server.quit()
According to POP3/SMTP compatible with 2 factor authentication? - Help - Gmail, you need to set up an "app password" to be used instead of your regular password to be able to use an SMTP client when "2-step verification" is turned on for your Google account.

How to forward email using Python

First, let me say, I already know that this was asked at Forwarding an email with python smtplib already.
The reason that I am posting something so closely related to that question is that I have tried using the answers to that question, I have tried changing things, I have searched Google and relentlessly monkeyed with this for about 5 hours now, and I am willing to spend a lot more time on this
-- I just thought one of you might have the answer though :)
My problem is as follows, I am trying to forward an email from my gmail to another gmail, and in running as many python script as I can to try this simple task, I still cannot figure it out.
Here is the code that I am running(this is my modified version of what was posted in the other form):
import smtplib, imaplib, email, string
imap_host = "imap.gmail.com"
imap_port = 993
smtp_host = "smtp.gmail.com"
smtp_port = 587
user = "John.Michael.Dorian.4"
passwd = "mypassword"
msgid = 1
from_addr = "John.Michael.Dorian.4#gmail.com"
to_addr = "myotheremail#gmail.com"
# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4_SSL(imap_host, imap_port)
client.login(user, passwd)
client.select()
typ, data = client.search(None, 'ALL')
for mail in data[0].split():
typ, data = client.fetch(msgid, "(RFC822)")
email_data = data[0][1]
client.close()
client.logout()
# create a Message instance from the email data
message = email.message_from_string(email_data)
# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
print message.as_string()
# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.set_debuglevel(1)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.quit()
The return from the SMTP debug says everything went okay, and I know that it is sending because I tried replacing the
smtp.sendmail(from_addr, to_addr, message.as_string())
With
smtp.sendmail(from_addr, to_addr, 'test')
And it worked fine. It prints the message.as_string() fine, and I am at a loss as how to get it to forward the email!
It doesn't have to be with SMTP or IMAP or any of this code(though it would be nice if it was) but I would really like to figure out how to do this.
I know its possible because I managed to do it yesterday, and the computer I was working on(running Windows of course) crashed and the file was gone.
For those of you who are wondering why I do not just set google to forward everything automatically, it is because I want a script that will eventually move a large amount of mail, once.
Thank you everyone!
More than likely, the Received: headers of the original email are causing gmail to drop the message. Try removing all of them before forwarding it.
If that doesn't fix it, print out the headers and code it to remove all of the ones that would not normally be there on a newly composed message.
However, why forward this way? It would be easier to just pull from one IMAP account and push it to another IMAP account directly.
In fact you could use Mozilla Thunderbird to add both accounts and just drag and drop the messages from one to the other.

Categories