how to send email with python after the google update? - python-3.x

I am using smtplib but after writing the code, been getting a bad credentials error and after changing email password and adding python to app passwords now i get a TimeoutError,
import smtplib
my_email = "ro21manrrereynolds349#gmail.com"
# password = "nqfpmxfgvrpunxku"
password = "6!OmRXMxLs8"
conn = smtplib.SMTP("smtp.gmail.com", port=465)
conn.ehlo()
conn.starttls()
conn.login(user=my_email, password=password)
conn.sendmail(
from_addr=my_email,
to_addrs="horisroman#gmail.com",
msg="Subject:Ola\n\nYou there."
)
conn.quit()
tried changing password, changing email, adding python to the app passwords, used email.mime.multipart but still got the same issues

Related

authentication error trying to send Outlook email from Python

I'm testing out a simple script to send an Outlook email from Python 3 (using Spyder).
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = 'my_username#my_company.com'
password = 'my_password'
mail_from = username
mail_to = username
mail_subject = "Test Subject"
mail_body = "This is a test message"
mimemsg = MIMEMultipart()
mimemsg['From']=mail_from
mimemsg['To']=mail_to
mimemsg['Subject']=mail_subject
mimemsg.attach(MIMEText(mail_body, 'plain'))
try:
connection = smtplib.SMTP(host='smtp.office365.com', port=587)
connection.starttls()
connection.login(username,password)
except Exception as e:
print('Got error here')
print(e)
And the output is:
Got error here
(535, b'Authentication unsuccessful, the user credentials were incorrect. [SOME_VALUE_HERE.hostname.prod.outlook.com]')
I know for sure my own username and email are correct - I verified by checking my username's properties > SMTP value. And anyway it's the username I use to login to Windows.
I'm also using the same password for logging into Windows.
Is it possible my company uses different values for host or port? Or on the backend it sends a different user name to the SMTP server?
The error indicates that SMTP authentication is disabled. Read more about that on the page at https://aka.ms/smtp_auth_disabled. The link explains how to enable SMTP AUTH for the whole organization or only for some mailboxes.
Also take a look at the following settings that would block Legacy Authentication:

Fbchat Login failed. Check email/password

from fbchat import Client
from fbchat.models import *
import json
import fbchat
from fbchat import Client
def main():
myUsername = "123456789"
myPassword = "987654321"
client = Client(myUsername, myPassword)
client.send(Message(text="text"), thread_id=xxxxxxxxxxxx, thread_type=ThreadType.USER)
if __name__ == '__main__':
main()
2 days ago I still logged in and created an automatic chat bot, but now, I can't login.
Error: fbchat._exception.FBchatUserError: Login failed. Check email/password. (Failed on url: https://m.facebook.com/checkpoint/?_rdr)
Can anyone help me fix this error or guide me to login = cookies, I have tried all the ways available on google but still not working.
example: https://github.com/fbchat-dev/fbchat/issues/477

Gmail API Reading credentials 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

I think there is an issue with Gmail API and Python3.
The original code in the documentation is in Python2, but for several reasons, including that my application is already working with Python3, I was passing the code to python3.
So... after sorting several issues, including a 400 request error, (which was apparently that the auth I provided to google wasn't corretly done) I'm facing (I hope) the final issue that apparently I'm trying to read a file but
Even just doing token.read() generates the same issue.
The token.pickle file is autogenerated once you've authorized google to access your email account and that the app can send emails automatically.
I know the credentials.json file is correct, as that's the point to tell google who you are and it always is reading my credentials correctly, redirecting me to give authorization to my app.
Here's the app to send emails, I think it's pretty straightforward, I followed the documentation and looked at other issues like this one and finally got this far:
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError
# from httplib2 import Http
# from oauth2client import client, tools, file
import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
from apiclient import errors
SCOPES = 'https://mail.google.com/'
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print(f'Message Id: {message["id"]}')
return message
except errors.HttpError as error:
print(f'An error occurred: {error}')
def CreateMessage(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
message_bytes = message.as_string().encode('utf-8')
# return { 'raw': base64.urlsafe_b64encode(message.as_string()) }
# return { 'raw': base64.urlsafe_b64encode(message_bytes) }
raw = base64.urlsafe_b64encode(message_bytes)
return raw.decode()
def main():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'r') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
# Create
message = CreateMessage('my-email#gmail.com', 'destination#gmail.com', 'Testing Gmail API', 'Hi GMAIL API')
# Send
SendMessage(service, "me", message)
if __name__ == '__main__':
main()
I truly don't know what to do here, if someone has already solved this issue and how.
THANKS!
In your script, when token.pickle is not created, Gmail API can be used by creating token.pickle at 1st authorization. But an error of 'raw' RFC822 payload message string or uploading message via /upload/* URL required occurs at message = (service.users().messages().send(userId=user_id, body=message).execute()). So in this case, please modify as follows.
From:
raw = base64.urlsafe_b64encode(message_bytes)
return raw.decode()
To:
raw = base64.urlsafe_b64encode(message_bytes).decode('utf-8')
return {'raw': raw}
After above modification, when your script is run as the 2nd run, when token.pickle, which has already been created, is read, an error occurs. I think that this error is in your title. In this case, please modify as follows.
From:
with open('token.pickle', 'r') as token:
To:
with open('token.pickle', 'rb') as token:
By this, I think that the script works.
By the way, if an error occurs when the code is retrieved, also please modify as follows.
From:
creds = flow.run_local_server(port=0)
To:
creds = flow.run_local_server()
Note:
About the authorization, you can see the sample script at the Quickstart of the official document.
If this was not the direction of your issue, I apologize.

Request module python

I'm having trouble using Python's request module.I'm trying to login to a webpage but it does not allow my connection.I don't really know if it might be a validation problem. Here is the code I'm using and the link of the page. It never shows me the page (The one I'm trying to access after I log in).
import requests
with requests.Session() as c:
username = "*******"
password = "******"
payload = {"userPri": username, "password": password}
url="https://declaraciones.sri.gob.ec/tuportalinternet/verificaEmail.jspa"
c.post("",data=payload)
page=c.get("another webpage")
print (page.content)`

Unable to change user's password via ldap3 Python3

Whenever I try to change someone's password via ldap3 library I get the following error:
{'type': 'modifyResponse', 'result': 53, 'message': '0000001F: SvcErr: DSID-031A12D2, problem 5003 (WILL_NOT_PERFORM), data 0\n\x00', 'referrals': None, 'description': 'unwillingToPerform', 'dn': ''}
This error usually occurs because of the two conditions: either user is trying to modify the password through the unencrypted connection or the password is being sent with the incorrect encoding. My SSL connection is fine (at least it seems to be):
print(connection)
>>> ldaps://DC1.DOMAIN.LOCAL:636 - ssl - user: DOMAIN\admin - not lazy - bound - open - <local: 172.16.10.2:49230 - remote: 172.16.10.254:636> - tls not started - listening - SyncStrategy - internal decoder
I tried to encode the string I'm trying send to the LDAP server, but .encode('utf-16le') didn't do the trick. Any other workarounds?
I have a test domain environment with Windows Server 2012 R2 as a domain controller, and the code I'm trying to change the password with is present below.
import ssl
from ldap3 import *
tls_configuration = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1_2)
s = Server('DC1.domain.local', get_info=ALL, use_ssl=True, tls=tls_configuration)
password = 'mypasswordhere'
c = Connection(s, user="DOMAIN\\admin", password=password)
c.open()
c.bind()
user = "CN=Dummy Dumass,OU=Automatically Generated,OU=Staff,OU=RU,DC=DOMAIN,DC=LOCAL"
c.modify(user, {
'unicodePwd': [(MODIFY_REPLACE, ['New12345'])]
})
print(c.result)
c.unbind()
ldap3 contains a specific method for changing AD password, use the following code instead of c.modify():
c.extend.microsoft.modify_password(user, new_password)
This code is working with Windows 2012 R2 AD:
pip install ldap
#!/usr/bin/python
import ldap3
SERVER='127.0.0.1'
BASEDN="DC=domain,DC=com"
USER="test-ms-ad#domain.com"
CURREENTPWD="current_password"
NEWPWD="new_password"
SEARCHFILTER='(&(|(userPrincipalName='+USER+')(samaccountname='+USER+')(mail='+USER+'))(objectClass=person))'
USER_DN=""
ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL)
conn = ldap3.Connection(ldap_server, USER, CURREENTPWD, auto_bind=True)
conn.start_tls()
print conn
conn.search(search_base = BASEDN,
search_filter = SEARCHFILTER,
search_scope = ldap3.SUBTREE,
attributes = ['cn', 'givenName'],
paged_size = 5)
for entry in conn.response:
if entry.get("dn") and entry.get("attributes"):
if entry.get("attributes").get("cn"):
USER_DN=entry.get("dn")
print USER_DN
print ldap3.extend.microsoft.modifyPassword.ad_modify_password(conn, USER_DN, NEWPWD, CURREENTPWD, controls=None)
The mentioned code is working for me, but changing password is only possible while using ssl. Change the server definition line as below:
ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL, use_ssl=True)

Resources