Tuesday, 12 August 2025

Sending Email from Python


 import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from datetime import datetime

# Convert DataFrame to HTML
html_table = df_errormessage.to_html(index=False)

# Custom statement
custom_statement = "<p>Please find the below error data:</p>"

# Combine statement and HTML table
email_body = f"{custom_statement}<br>{html_table}"

# Get current date
current_date = datetime.now().strftime("%Y-%m-%d")

smail = 'do.not.reply@company.com'
tmail = ['123@company.com', '456@company.com']
sub = f'Error Report - {current_date}'

def send_mail(send_from, send_to, subject, text, isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = ','.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    # Attach the HTML table to the email body
    msg.attach(MIMEText(email_body, 'html'))

    smtp = smtplib.SMTP('outlook.company.com')
    if isTls:
        smtp.starttls()
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

# Send the email if the condition is met
send_mail(smail, tmail, sub, text)
print(df_errormessage)

Setting environmental variables using .env file in Python

 STEP-1 - Finding the Root path of your python code


import os
# Get the current working directory
cwd = os.getcwd()
print(cwd)

Output




STEP-2 -Creating Env files

  • After getting root path folder, create a file names .env file in that folder as shown below






STEP-3 -Entering credential details in .env File

  • you can enter all the secure details in env file as shown below.



Friday, 1 August 2025

Python code to read Blob Files

 

from azure.storage.blob import BlobServiceClient
import pandas as pd

# Azure Blob Storage connection string
connection_string = 'Connection String'

# Initialize the BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(connection_string)

# Container names
containers = ['b2barchive', 'b2bbadfiles']

# Dictionary to store DataFrames for each container
dfs = {}

for container_name in containers:
    # Get the container client
    container_client = blob_service_client.get_container_client(container_name)

    # List all blobs in the container
    print(f"Listing blobs in the container: {container_name}")
    blob_list = container_client.list_blobs()

    # Create a list to store blob names and last modified dates
    blob_data = []

    for blob in blob_list:
        print(f"Blob Name: {blob.name}, Last Modified: {blob.last_modified}")
        blob_data.append({'Blob Name': blob.name, 'Last Modified': blob.last_modified})

    # Create a DataFrame from the list of blob data
    dfs[container_name] = pd.DataFrame(blob_data)

# Specify the full path to save the Excel file
output_excel_file = r'C:\Users\kar\Desktop\B2B File Details\blob_list.xlsx'

# Write the DataFrames to separate sheets in an Excel file
with pd.ExcelWriter(output_excel_file) as writer:
    for container_name, df in dfs.items():
        df.to_excel(writer, sheet_name=container_name, index=False)

print(f"Blob lists have been written to {output_excel_file}")


To find your Azure Storage account key, follow these steps:

Steps to Find Your Azure Storage Account Key

  1. Log in to the Azure Portal:

  2. Navigate to Your Storage Account:

    • In the left-hand menu, click on "Storage accounts" to see a list of your storage accounts.
    • Click on the storage account you want to use (e.g., strorageaccountanme).
  3. Access the Access Keys:

    • In the storage account's menu, under the "Settings" section, click on "Access keys".
    • You will see two access keys (key1 and key2) and their corresponding connection strings.
  4. Copy the Account Key:

    • Copy one of the account keys (either key1 or key2). You can use this key in your connection string.

Example Connection String

Once you have your account key, you can construct your connection string. For example, if your account key is , your connection string would look like this:

connection_string = 'DefaultEndpointsProtocol=https;AccountName=strorageaccountanme;AccountKey=acceountkey