BC Emails
BC Emails

BC Emails

Juli 17, 2024
python logo

Automating email sending can save a lot of time and effort, especially if you have a list of customers or clients that you need to contact regularly. Using Python, we can create a script that will send emails to a list of customers stored in an Excel file without using CC or BCC, so each email will be sent individually. This article will guide you step by step on how to create such a script using the pandas library to read data from Excel and smtplib to send emails.

Setting Up the Environment

  1. Install Python: If not already installed, download and install Python from the official website.
  2. Install Required Libraries: Run the following command in the terminal or command prompt to install pandas and openpyxl:
    pip install pandas openpyxl

Excel File Format

Ensure your Excel file has the correct format. A suggested format is as follows:

Title Name Email
Mr John Doe john.doe@example.com
Ms Jane Smith jane.smith@example.com
Mr Bob Johnson bob.johnson@example.com

Python Script to Send Emails

Create a new Python file, for example, send_emails.py, and add the following code:

import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Function to send email
def send_email(to_address, subject, body, from_address, password):
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    
    try:
        # Connect to SMTP server (example: Gmail)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(from_address, password)
        server.sendmail(from_address, to_address, msg.as_string())
        server.close()
        print(f"Email sent to {to_address}")
    except Exception as e:
        print(f"Failed to send email to {to_address}: {e}")

# Read data from Excel file
excel_file = 'customer_emails.xlsx'  # Replace with your Excel file name
data = pd.read_excel(excel_file)

# Sender information
from_address = 'your_email@gmail.com'  # Replace with your email
password = 'your_email_password'       # Replace with your email password
subject = 'Introducing New Product'
body_template = '''
Dear {title} {name},

We from [Your Company] would like to introduce our latest product to you. [Product Description].

Best regards,
[Your Name]
'''

# Send email to each customer
for index, row in data.iterrows():
    to_address = row['Email']
    title = row['Title']
    name = row['Name']
    body = body_template.format(title=title, name=name)
    send_email(to_address, subject, body, from_address, password)
#dengan attachment
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os

# Fungsi untuk mengirim email dengan lampiran
def send_email(to_address, subject, body, from_address, password, attachment_path=None):
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    
    if attachment_path:
        try:
            with open(attachment_path, 'rb') as attachment:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(attachment.read())
                encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    f'attachment; filename= {os.path.basename(attachment_path)}',
                )
                msg.attach(part)
        except Exception as e:
            print(f"Failed to attach file {attachment_path}: {e}")

    try:
        # Menghubungkan ke server SMTP (contoh: Gmail)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(from_address, password)
        server.sendmail(from_address, to_address, msg.as_string())
        server.close()
        print(f"Email sent to {to_address}")
    except Exception as e:
        print(f"Failed to send email to {to_address}: {e}")

# Membaca data dari file Excel
excel_file = 'customer_emails.xlsx'  # Ganti dengan nama file Excel Anda
data = pd.read_excel(excel_file)

# Informasi pengirim
from_address = 'your_email@gmail.com'  # Ganti dengan email Anda
password = 'your_email_password'       # Ganti dengan password email Anda
subject = 'Perkenalan Produk Baru'
body_template = '''
Yth. {title} {name},

Kami dari [Nama Perusahaan] ingin memperkenalkan produk terbaru kami kepada Anda. [Deskripsi Produk].

Salam hormat,
[Nama Anda]
'''
attachment_path = 'attachment_file.pdf'  # Ganti dengan nama file lampiran Anda

# Mengirim email ke setiap pelanggan
for index, row in data.iterrows():
    to_address = row['Email']
    title = row['Title']
    name = row['Name']
    body = body_template.format(title=title, name=name)
    send_email(to_address, subject, body, from_address, password, attachment_path)

Script Explanation

Libraries Used:

  • pandas: To read data from the Excel file.
  • smtplib: To send emails.
  • email.mime: To create the email content.

Function send_email: Sends an email with parameters for the recipient's address, subject, body, sender's address, and password.

Reading Data: Reads the Excel file and retrieves each row to send an email.

Email Template: Uses a template string for the email content, which will be personalized for each customer.

Running the Script

Run the script with the following command in the terminal or command prompt:

python send_emails.py

Important Notes

  • Security: Do not store your email password directly in the script. Use environment variables or other secure methods.
  • SMTP Server: The example uses Gmail's SMTP server. If you use another email service, make sure to configure the SMTP server accordingly.
  • Data Backup: Always back up your data before running scripts that modify or access sensitive information.

By following the steps above, you can automatically send emails to all customers in your list without using CC or BCC, saving you time as a sales or business manager.