Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are we using Square Brackets in python to access MIMEMultipart() components like ['From'], ['To'] for sending email using python?

In a python code, which is sending an email using "smtplib" and "MIMEMultipart" libraries,

I got a doubt on, why we are using "square brackets" for [‘From’], [‘To’] and [‘Subject’] when referring to "MIMEMultipart ()". Could any anyone explain on this part ?

Below is the code snipet, observe the commenting lines :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
mail_content = '''Hello,This is a test mail.'''
sender_address = 'xyz710@gmail.com'
sender_pass = 'wesqabfucxfqcg'
receiver_address = 'abcd12@gmail.com'

#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address #  ** why are we using square bracket [] here ?? **
message['To'] = receiver_address # ** why are we using square bracket [] here ?? **
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
# **why are we using square bracket [] here ?? **

message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'TP_python_prev.pdf'
attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload) #encode the attachment
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

>Solution :

You’re not accessing; you’re setting.

MIMEMultipart defines a magic method __setitem__ which defines the syntax for OBJECT[key] = value

The conceptual model provided by an EmailMessage object is that of an ordered dictionary of headers coupled with a payload that represents the RFC 5322 body of the message

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading