0

How can I, using the dictionary (contacts), modify the code in a way that allows sending an e-mail by providing the name and surname of the addressee.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

contacts = {
   "john.david@gmail.com" : "Rick Jones",

}

msg = MIMEMultipart()
msg['From'] = 'xxx'
msg['To'] = 'xxx'
msg['Subject'] = 'hello'
message = ("hi")
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login('xxx', 'xxx')

mailserver.sendmail('xxx','xxx',msg.as_string())

mailserver.quit()
  • You mean getting the email from value `"Rick Jones"` ? – azro Apr 12 '21 at 19:30
  • Does this answer your question? [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – azro Apr 12 '21 at 19:31

1 Answers1

0

If you're having the user provide the name and surname. You could do something like this.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

contacts = {
    "rick jones":"rick.jones@gmail.com" ,

}
send_to = ""
while send_to == "":
    name = input("Please enter the full name of an email contact").lower()
    if name in contacts:
        send_to = contacts[name]


msg = MIMEMultipart()
msg['From'] = 'xxx'
msg['To'] = send_to
msg['Subject'] = 'hello'
message = ("hi")
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login('xxx', 'xxx')

mailserver.sendmail('xxx',send_to,msg.as_string())

mailserver.quit()

Basically I would just just use the user input as the key in the dictionary that resolves to the email address of the receiver. So I switched the key/data in your dictionary. Cause you want the user to enter their first name in order to pull up their email address. So I believe the key would be best suited as the persons full name entered by the user, cause it will have direct 1:1 access to the email address/es stored for that name.

If that name comes back with multiple email addresses (Because in your dictionary that name might be associated with more than one email address) you can store them as a tuple or list and ask the user which one they meant by iterating through "contacts[name]".

Cody H
  • 1
  • 1