简体   繁体   中英

How to send multiple emails in a loop with attachments using Python

Hello, can anyone help me out to write a code which helps me to send multiple emails with attachments in loops at once?

Now I am explaining what I exactly want to achieve.

This is my table available in excel sheet

enter image description here

Step 01 - I have multiple excel report saved in folder with the same name as the Emp Number as mentioned in above table.

Step 02 - so I want want code such as it will pick the report from folder by matching report name with the Emp Number mentioned in table and send mail to Email id which is available against those Emp Number

note: report name and Emp Number both is same.

It is possible because right now I am sending more than 3210+ emails manually , which is exhausting me.

Supposing the usage of Outlook for Windows as application to send emails, and you have some table which you want to send called dataset , and a list of emails called emails :

Initialize the Outlook application, make sure that you have opened it alrealdy before starting the script:

import win32com.client as win32
olApp = win32.Dispatch("Outlook.Application")
olNS = olApp.GetNameSpace("MAPI")
email_sender = "your.email@xxx.xxx"

Creating an email object (empty):

mail_item = olApp.CreateItem(0)

Supposing you want to send a shared email to everyone in copy you can do:

mail_item.To = "; ".join(emails)

Otherwise, if you want to email singularly just loop to email or use multithreading which is more appropriate/fast rather than multiprocessing for this kind of tasks.

mail_item.Subject = "An unusual email."
mail_item.BodyFormat = 1
mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, olNS.Accounts.Item(email_sender)))

Then, initialize your body as a string:

body = ""

Think about a static header which will describe the email and the content of the table and add it to the body:

body += """<td style="line-height:15px;font-family:Arial;mso-line-height-rule:exactly;padding-bottom:5px">{}</td></br>""".format("A Random Header.")

Again, add to the body the pandas table with the .to_html() to parse it correctly as html:

body += """<br><pre>{}</br></pre>""".format(dataset.to_html())

Give the body to the mail_item :

mail_item.HTMLBody = "<html><body>{}</html></body>".format(body)

Send the email:

mail_item.Send()

Considering that you have a @gmail address, you can run the code below to send multiple emails with different ExcelFiles attachements (stored in one single folder) to different recipients (including non-gmail addresses).

import pandas as pd
import smtplib
from email.message import EmailMessage

df = pd.read_excel(r'path\\to\\your\\emails_Excelfile.xlsx')

for index, row in df.iterrows():
    emp_number = row['EMP Number']
    email_id = row['Email ID']
    msg = EmailMessage()
    msg['Subject'] = 'Report number ' + str(emp_number)
    msg['From'] = 'put_your_@gmail_here'
    msg['To'] = email_id
    msg.set_content("Put your message here")
    
    with open(fr"path\\to\\reportsFolder\{emp_number}.xlsx", 'rb') as f:
        file_data=f.read()
        file_name=f.name
        msg.add_attachment(file_data, maintype='application', subtype='xlsx', filename=file_name)
    
    try:
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            server.login('put_your_@gmail_here', 'put_your_AppPassword_here')
            server.send_message(msg)
    except:
        pass
>>> Result

在此处输入图像描述

VERY IMPORTANT:

Since the "Access for the less secure app" in Gmail has been deactivated by Google, you have to generate an APP password so smtplib can login your gmail. And to do this, you need to:

  1. Open up Google Account (after your sign-in)
  2. Under the "Signing in to Google" section, activate the "2-Step Verification"
  3. Create an app password (to get a sixteen string characters)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM