I would like to merge data so I can send only one email
for body in result:
msg = EmailMessage()
msg.set_content(body)
msg['From'] = email_address
msg['To'] = recipient_address
msg['Subject'] = subject_desc
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("[email protected]", password)
print("login success")
server.send_message(msg)
print("This message has been sent")
server.quit()
This code actually sends me a dozen of single email with data I got from result
as it's in a loop but I would like to get one single email for those dozen of data.
I tried something like this :
def email(body):
data = []
for body in result:
data.append(body)
return data
but it's still sending dozen of email instead of one how could I do it ?
Thank you by advance :)
CodePudding user response:
If you have list with many strings then create one string
body = "\n".join(result)
and send without for
-loop.
msg = EmailMessage()
body = "\n".join(result)
#body = "\n---\n".join(result) # to separate result with line `---`
msg.set_content(body)
msg['From'] = email_address
msg['To'] = recipient_address
msg['Subject'] = subject_desc
If you have list with filenames then you can use for
-loop but with different indentation.
It is example for sending only images. For other type of files it would need different maintype
,subtype
filenames = ['images/lenna.jpg', 'images/cats.jpg']
# ...
msg = EmailMessage()
for name in filenames:
msg.add_attachment(open(name, 'rb').read(), filename=name, maintype='text', subtype='jpg')
msg['From'] = email_address
msg['To'] = recipient_address
msg['Subject'] = subject_desc
Or you can use other module to guess type
import mimetypes
# ... code ...
for name in filenames:
ctype, encoding = mimetypes.guess_type(name)
print(name, ctype, encoding)
maintype, subtype = ctype.split('/')
msg.add_attachment(open(name, 'rb').read(), filename=name, maintype=maintype, subtype=subtype)
Of course you can also use set_content()
and add_attachment()
in the same mail.
It can be used to send HTML with images - but I skip this example.