Created
September 5, 2025 07:43
-
-
Save RANUX/f48d934ed45e778cdd28c4870d4701e8 to your computer and use it in GitHub Desktop.
Send email using python exchangelib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
from exchangelib import Account, Configuration, Credentials, DELEGATE, Mailbox, Message | |
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter | |
from dotenv import load_dotenv | |
import os | |
load_dotenv() | |
# Отключение проверки SSL сертификатов (если необходимо) | |
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter | |
# Global variables for email credentials | |
EMAIL_USER = os.getenv("EMAIL_USER") | |
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD") | |
EMAIL_PRIMARY_SMTP_ADDRESS = os.getenv("EMAIL_PRIMARY_SMTP_ADDRESS") | |
# Подключение с автодискавери | |
credentials = Credentials(username=EMAIL_USER, password=EMAIL_PASSWORD) | |
config = Configuration( | |
server="x.x.x.x", # e.g., 'outlook.office365.com' | |
credentials=credentials, | |
auth_type=os.getenv("AUTH_TYPE", "NTLM"), # or 'Basic' depending on your setup | |
) | |
account = Account( | |
primary_smtp_address=EMAIL_PRIMARY_SMTP_ADDRESS, | |
credentials=credentials, | |
config=config, | |
access_type=DELEGATE, | |
# autodiscover=True, # alt way to get exchange address without server address | |
) | |
# Получение URL Exchange сервера | |
ews_url = account.protocol.service_endpoint | |
print(f"----> Exchange server URL: {ews_url}") | |
# Получение типа аутентификации и версии | |
ews_auth_type = account.protocol.auth_type | |
version = account.version | |
server_name = ews_url.split("//")[1].split("/")[0] | |
try: | |
# Получение основного IP адреса | |
server_ip = socket.gethostbyname(server_name) | |
print(f"Exchange server IP: {server_ip}") | |
# Получение всех IP адресов (для серверов с несколькими адресами) | |
all_ips = socket.gethostbyname_ex(server_name) | |
print(f"All server IPs: {all_ips[2]}") | |
except socket.gaierror as e: | |
print(f"DNS resolution failed: {e}") | |
# Создание сообщения | |
message = Message( | |
account=account, | |
folder=account.sent, | |
subject="Test email SSPI", | |
body="Test email text", | |
to_recipients=[ | |
Mailbox(email_address="[email protected]"), | |
], | |
) | |
# Отправка письма | |
try: | |
message.send_and_save() | |
print("Mail sent") | |
except Exception as e: | |
print(f"{e}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment