I’m working with the below code to send emails to people in python.
import smtplib
from email.mime.multipart import MIMEMultipart, MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
def send_mail(send_from,send_to, subject, text, files=[], server = "localhost"):
for s in send_to:
COMMASPACE = ', '
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(s)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' %os.path.basename(f))
msg.attach(part)
server = smtplib.SMTP(server)
server.sendmail(send_from, s, msg.as_string())
server.close()
Sorry for the formatting if it’s messed up. emails is a pre-defined list with two emails. The error I’m encountering is:
AttributeError: SMTP instance has no attribute ‘find’
Any idea? Thanks in advance.
You don’t need to create a separate email message for each recipient; just send a single message with multiple recipients:
This is almost identical to the example “Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory” in the docs.
(If you don’t want each person to see the other’s addresses, you can make them all
BCCs instead ofTos.)If you’re more interested in what’s wrong with your original code, than with how to do it properly, there are two immediately visible problems:
joining each address, as Vader explains.SMTP.sendmail, but the second argument is a sequence of addresses. To fix that, use[s]instead ofs, as most of the examples do.Both of these are caused by the same confusion, treating each address as a list of addresses. You may have additional errors caused by the same problem.