Uncategorized

email – Mail Merge Function with Python


I have a problem with the code below, it copies the information from the Wolrd file in half, because I have images in the file and it doesn’t copy them.

Another important point is that it is not copying with Wordold formatting, the text has specific formatting in the title and paragraphs, my idea is that the code should copy and paste the content preserving the formatting, but this is not happening as I would like.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from docx import Document
import openpyxl
import config
import html2text

def read_excel_info(file_path):
    print("Reading Excel information...")
    wb = openpyxl.load_workbook(file_path)
    sheet = wb.active

    # Initialize lists to store information
    names = []
    emails = []
    titles = []

    # Iterate over rows in columns A, B, and C
    for row in sheet.iter_rows(min_row=2, max_col=3, max_row=sheet.max_row, values_only=True):
        name, email, title = row[0], row[1], row[2]
        print(f"Name: {name}, Email: {email}, Title: {title}")
        names.append(name)
        emails.append(email)
        titles.append(title)

    wb.close()
    return names, emails, titles

def read_word_content(file_path):
    print("Reading Word content...")
    doc = Document(file_path)
    html_text = ""
    for paragraph in doc.paragraphs:
        html_text += f"<p>{paragraph.text}</p>"

    return html_text

def convert_html_to_text(html):
    print("Converting HTML to text...")
    # Convert HTML to text while preserving line breaks
    converter = html2text.HTML2Text()
    converter.body_width = 0
    formatted_text = converter.handle(html)

    return formatted_text

# SMTP server settings
smtp_host = config.smtp_server
smtp_port = 587
your_email = config.user
your_password = config.password

# Excel information
excel_path="Configuração E-mail.xlsx"
names, emails, titles = read_excel_info(excel_path)

# Word content
word_path="Teste.docx"
email_body_html = read_word_content(word_path)
email_body_text = convert_html_to_text(email_body_html)

# Connect to SMTP server and send emails
with smtplib.SMTP(smtp_host, smtp_port) as server:
    print("Connecting to SMTP server...")
    server.starttls()
    server.login(your_email, your_password)

    # Iterate over recipients
    for name, email, title in zip(names, emails, titles):
        # If email is not None and is a valid email address
        if email and '@' in email:
            print(f"Sending email to {email}...")
            # Create email
            msg = MIMEMultipart()
            msg['Subject'] = title
            msg['From'] = your_email
            msg['To'] = email

            # Add email body as text
            email_body_mime = MIMEText(email_body_text, 'plain', 'utf-8')
            msg.attach(email_body_mime)

            # Add Word file as attachment
            with open(word_path, 'rb') as file:
                attachment = MIMEApplication(file.read(), _subtype="docx")
                attachment.add_header('Content-Disposition', 'attachment', filename=word_path)
                msg.attach(attachment)

            # Send email
            server.sendmail(your_email, email, msg.as_string())
            print(f"Email sent successfully to {email}!")

print('Emails sent successfully!')



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *