How to add multiple recipients to this email code?

209 views Asked by At
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "YOUR EMAIL"
toaddr = ["FISRT EMAIL ADDRESS YOU SEND TO", "SECOND EMAIL ADDRESS YOU SEND TO"]

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"

body = "TEXT YOU WANT TO SEND"

msg.attach(MIMEText(body, 'plain'))

filename = "NAME OF THE FILE WITH ITS EXTENSION"
attachment = open("PATH OF THE FILE", "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")

this is where i get an errot saying that a list element cannot be encoded text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()

1

There are 1 answers

0
Vinay_Systematix On

If you want to add multiple recipients in email then you should fetch user from database and add in to the loop.

import System.Net;

import System.Net.Mail;

  1. Fetch the user data based on your condition. enter code herevar data = dataContext.website_request_logs.Where("condition");// we use datacontext to fetch data from website_request_logs table.

  2. foreach (website_request_log item in data) string EmailTo = item.email; string EmailFrom = item.fromEmail; string EmailSubject = item.emailSubject;

  3. EmailUser(EmailTo ,EmailFrom ,EmailSubject );// call the function and send parameter in this.

4.// we can use Email helper class to send email.

`private void EmailUser ( string EmailTo, string EmailFrom, string EmailSubject ) {

         EmailHelper.SendEmail
                    (EmailFrom,
                    EmailTo,
                   EmailSubject,
                   );



    }`
  1. SendEmail(){MailMessage msg = new MailMessage(); msg.From = new MailAddress(fromEmail, fromName);

    mail.Send(msg);

}