python sendemail script expecting authenication - python-3.x

I trying send email via python script with my company email id or donotreply#company.com.
Scripting throwing error you must authenticate.
python3 sendemail.py
Traceback (most recent call last):
File "sendemail.py", line 99, in <module>
sendemail(from_addr, to_addr_list, subject, cc_addr_list, message,
smtpserver="mail.company.net")
File "sendemail.py", line 73, in sendemail
problems = server.sendmail(from_addr, to_addr_list, message)
File "/usr/lib/python3.6/smtplib.py", line 867, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (503, b'you must authenticate first
(#5.5.1)', 'user#company.com')
Please suggest what exactly issue happening same step in jenkins test email works.

Related

Winrs works while pywinrm module returns "the specified credentials were rejected by the server" error

I have a setup where I can winrs to the remote machine successfully without issues. However when I use pywinrm, I get an error about credentials.
Here is the authentication details of the remote windows the machine.
How one would go debugging this issue?
winrm get winrm/config/service/auth
Auth
Basic = false [Source="GPO"]
Kerberos = true [Source="GPO"]
Negotiate = false [Source="GPO"]
Certificate = false
CredSSP = false [Source="GPO"]
CbtHardeningLevel = Strict [Source="GPO"]
I tried this both from windows and linux and I get the same result. From the windows machine I can do winrs without issues.
Windows output:
import winrm
sess = winrm.Session('<hostname>', auth=('MOzsoy', '***'), transport='kerberos')
sess.run_cmd('hostname')
Traceback (most recent call last):
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\winrm\transport.py", line 328, in _send_message_request
response.raise_for_status()
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: for url: http://<hostname>:5985/wsman
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\winrm\__init__.py", line 40, in run_cmd
shell_id = self.protocol.open_shell()
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\winrm\protocol.py", line 166, in open_shell
res = self.send_message(xmltodict.unparse(req))
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\winrm\protocol.py", line 243, in send_message
resp = self.transport.send_message(message)
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\winrm\transport.py", line 322, in send_message
response = self._send_message_request(prepared_request, message)
File "C:\Users\mozsoy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\winrm\transport.py", line 332, in _send_message_request
raise InvalidCredentialsError("the specified credentials were rejected by the server")
winrm.exceptions.InvalidCredentialsError: the specified credentials were rejected by the server
Linux output:
import winrm
sess = winrm.Session('<hostname>', auth=('MOzsoy', '***'), transport='kerberos')
sess.run_cmd("hostname")
/home/mozsoy/.local/lib/python3.7/site-packages/winrm/vendor/requests_kerberos/kerberos_.py:176: NoCertificateRetrievedWarning: Requests is running with a non urllib3 backend, cannot retrieve server certificate for CBT
NoCertificateRetrievedWarning)
Traceback (most recent call last):
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/transport.py", line 328, in _send_message_request
response.raise_for_status()
File "/usr/lib/python3/dist-packages/requests/models.py", line 840, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: for url: http://<hostname>:5985/wsman
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/__init__.py", line 40, in run_cmd
shell_id = self.protocol.open_shell()
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/protocol.py", line 166, in open_shell
res = self.send_message(xmltodict.unparse(req))
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/protocol.py", line 243, in send_message
resp = self.transport.send_message(message)
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/transport.py", line 309, in send_message
self.build_session()
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/transport.py", line 292, in build_session
self.setup_encryption()
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/transport.py", line 298, in setup_encryption
self._send_message_request(prepared_request, '')
File "/home/mozsoy/.local/lib/python3.7/site-packages/winrm/transport.py", line 332, in _send_message_request
raise InvalidCredentialsError("the specified credentials were rejected by the server")
winrm.exceptions.InvalidCredentialsError: the specified credentials were rejected by the server
It seems that pywinrm doesn't like this setting:
CbtHardeningLevel = Strict [Source="GPO"]
As it is configured through GPO, you probably need to contact your admin about this.
From what I found so far, pywinrm can't handle "Strict", but you need to use "Relaxed"
I encounterd this for Ansible, but I guess it's due to pywinrm.
https://github.com/diyan/pywinrm/issues/109
https://docs.ansible.com/ansible/latest/user_guide/windows_setup.html#http-401-credentials-rejected

How to use Microsoft Online Exchange with python to send mail

I want to send an Email from my outlook account using Python. I used the below code running in an AWS EC2 instance to generate an email.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login("<outlook_mail_id>","<outlook_password>")
server.sendmail("<outlook_mail_id>", "<recipient_email_id> ", "Test Message")
server.quit()
But while running this I get the below error
Traceback (most recent call last):
File "smtp_office_365.py", line 12, in <module>
server.login("<outlook_email_id>","<outlook_pass>")
File "/usr/local/lib/python3.8/smtplib.py", line 734, in login
raise last_exception
File "/usr/local/lib/python3.8/smtplib.py", line 723, in login
(code, resp) = self.auth(
File "/usr/local/lib/python3.8/smtplib.py", line 646, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [MN2PR15CA0001.namprd15.prod.outlook.com]')
I am able to login into web outlook account using these credentials. Hence to check further I connected with my Admin team and they said that Basic Authentication is disabled for this account and can't be enabled in any case. They suggested me to use modern Authentication method by using Microsoft Online Exchange.
On further exploration I found the below script to send the mail
from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, Configuration
credentials = Credentials('<outlook_mail_id>', '<outlook_password>')
account = Account('<outlook_mail_id>', credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)
But I get the below error while running the script
Traceback (most recent call last):
File "test_exchange.py", line 5, in <module>
account = Account('<outlook_email_id>', credentials=credentials, autodiscover=True)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/account.py", line 116, in __init__
self.ad_response, self.protocol = discover(
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 24, in discover
return Autodiscovery(
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 123, in discover
ad_response = self._step_1(hostname=domain)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 433, in _step_1
return self._step_2(hostname=hostname)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 451, in _step_2
return self._step_3(hostname=hostname)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 483, in _step_3
return self._step_4(hostname=hostname)
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 514, in _step_4
return self._step_6()
File "/home/ec2-user/.local/lib/python3.8/site-packages/exchangelib/autodiscover/discovery.py", line 572, in _step_6
raise AutoDiscoverFailed(
exchangelib.errors.AutoDiscoverFailed: All steps in the autodiscover protocol failed for email '<outlook_email_id>'. If you think this is an error, consider doing an official test at https://testconnectivity.microsoft.com
Please let me know if more details are required. Any help would be appreciated.
Thanks

Error in trying to create a topic subscription in Google PubSub python

I am trying to create a subscription to a topic using Google's pubsub_v1 library in python. I have successfully created a topic using the library (I can see it in the cloud console after creation). However I am having an issue trying to create a subscription. I tried to solution given in this question to no avail. Here is my subscription code:
from google.cloud import pubsub_v1 as pubsub
topic_name = 'logs'
sub_name = 'logs-consumer'
project_name = 'my-project' # valid project name
subscriber = pubsub.SubscriberClient()
topic_path = subscriber.topic_path(project_name, topic_name)
subscription_path = subscriber.subscription_path(project_name, sub_name)
# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
subscription = subscriber.create_subscription(
request={"name": subscription_path, "topic": topic_path}
)
Whenever I run this code, I get the following error:
Traceback (most recent call last):
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.INVALID_ARGUMENT
details = "Project 'project:gcp-python-291817' not found or deleted."
debug_error_string = "{"created":"#1607133732.705528000","description":"Error received from peer ipv6:[2607:f8b0:400f:801::200a]:443","file":"src/core/lib/surface/call.cc","file_line":1062,"grpc_message":"Project 'project:gcp-python-291817' not found or deleted.","grpc_status":3}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "logger_consumer_GCP.py", line 28, in <module>
request={"name": subscription_path, "topic": topic_path}
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/cloud/pubsub_v1/_gapic.py", line 40, in <lambda>
fx = lambda self, *a, **kw: wrapped_fx(self.api, *a, **kw) # noqa
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/pubsub_v1/services/subscriber/client.py", line 526, in create_subscription
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
on_error=on_error,
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/Users/zacharymcgrath/Library/Python/3.7/lib/python/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Project 'project:gcp-python-291817' not found or deleted.
I thought it might be that my project gcloud variable had somehow changed and the library uses environment variables, but I double checked and it was correct. I'm not really sure what I'm doing thats different than the question referred to above. Thanks.
Update
Some helpful information from the comments:
gcp-python-291817 is not the name of the project
the project name is in a config file that both the publisher and the subscriber read from. The publisher did not have any problems when reading the project name from the file and publishing a message
I had a ssh configuration for a VM instance within this project named gcp-python, but was removed a while ago
clearing the gcloud cache and gsutils cache has not fixed the problem either
I found the issue. I re-ran
gcloud auth application-default login
and made sure that GOOGLE_APPLICATION_CREDENTIALS was pointed to the new credentials json file and it worked. I must have messed up the credentials file at some point. Thanks for the help!

exchangelib KeyError: 'contacts' or KeyError: 'inbox' or

I want to search in contact list of some account and get that contacts details back, but none of folders that told here not work because of KeyError exception .
Somehow i can't access to any of exchange account folders.
Is it permission or ... ?
Code :
from exchangelib import Credentials, Account, Configuration
from exchangelib.protocol import NoVerifyHTTPAdapter, BaseProtocol
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
credentials = Credentials("YYY#XXX.com", 'PASSWORD')
account = Account(
primary_smtp_address="Account#XXX.com",
autodiscover=True,
credentials=credentials
)
print(account) # work properly with printing my account
print(account.contacts) # not work with KeyError Exception
Error :
Warning (from warnings module):
File "C:\Python\lib\site-packages\urllib3\connectionpool.py", line 857
InsecureRequestWarning)
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
Traceback (most recent call last):
File "C:\Python\lib\site-packages\cached_property.py", line 69, in __get__
return obj_dict[name]
KeyError: 'contacts'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\dvp7\Desktop\ex.py", line 20, in <module>
print(account.contacts)
File "C:\Python\lib\site-packages\cached_property.py", line 73, in __get__
return obj_dict.setdefault(name, self.func(obj))
File "C:\Python\lib\site-packages\exchangelib\account.py", line 169, in contacts
return self.root.get_default_folder(Contacts)
File "C:\Python\lib\site-packages\exchangelib\folders.py", line 965, in get_default_folder
for f in self._folders_map.values():
File "C:\Python\lib\site-packages\exchangelib\folders.py", line 928, in _folders_map
for f in FolderCollection(account=self.account, folders=distinguished_folders).get_folders():
File "C:\Python\lib\site-packages\exchangelib\services.py", line 1053, in call
shape=shape,
File "C:\Python\lib\site-packages\exchangelib\services.py", line 88, in _get_elements
response = self._get_response_xml(payload=payload)
File "C:\Python\lib\site-packages\exchangelib\services.py", line 189, in _get_response_xml
raise rme
File "C:\Python\lib\site-packages\exchangelib\services.py", line 171, in _get_response_xml
res = self._get_soap_payload(soap_response=soap_response_payload)
File "C:\Python\lib\site-packages\exchangelib\services.py", line 227, in _get_soap_payload
cls._raise_soap_errors(fault=fault) # Will throw SOAPError or custom EWS error
File "C:\Python\lib\site-packages\exchangelib\services.py", line 261, in _raise_soap_errors
raise vars(errors)[code](msg)
exchangelib.errors.ErrorInternalServerError: An internal server error occurred. The operation failed.
Build version :
Build=15.0.847.31, API=Exchange2013_SP1, Fullname=Microsoft Exchange Server 2013 SP1
This method is work :
account.root.walk() # output : <exchangelib.folders.FolderCollection object at 0x03ADCA90>
But when i append filter to it above error occurred.
KeyError: 'folders'
only root folder is works fine and there is nothing in it !
print(account.root.all()) # QuerySet(q=Q(), folders=[Root (root)])
For the record, this turned out to be a misbehaving archive inbox folder. Workaround provided in https://github.com/ecederstrand/exchangelib/issues/431#issuecomment-409832287 by telling exchangelib to ignore this folder:
from exchangelib.folders import ArchiveInbox
from exchangelib.version import EXCHANGE_2016
# Set to something newer than your current version
ArchiveInbox.supported_from = EXCHANGE_2016
For those who find this issue by searching for:
exchangelib KeyError: 'inbox'
the fix for us was to upgrade past 1.11.4. The was necessary after 9:15 am PST today

How would I send a message to a specific channel [Discord.py]

I have been trying to make a discord bot that reacts to messages in a certain channel. However I have not been able to achieve it with my current code. I was told to use get_channel and I tried a couple different ways and it has not work. So How would I use get_channel to only react to messages in a certain channel?
if message.content.startswith('#'):
currevents = get_channel(273977792159416321)
if message.channel is currevents:
await client.add_reaction(message, ":nocheck:432565697349025803")
await client.add_reaction(message, ":yescheck:432565678529052672")
This is the error I get:
Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/discord/client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "APSIAbot.py", line 28, in on_message
currevents = get_channel("273977792159416321")
NameError: name 'get_channel' is not defined

Resources