'Python smtplib send email to recipient in correspondant row
Is there a way to send a mail with python smtplib whose recipient varies by row in a dataframe? (one to one mail) I can send a different message by row, but I cant replicate the same with the receiver, since I can only send them either to one, or to all of the receivers that I mention. I cant send it to the receiver in the correspondant row. I have the following code:
for each_line in df.index:
z = message (its an example... this part is like df['first column'] + " hello " + df['second column'])
MY_ADDRESS = "[email protected]"
MY_PASSWORD = "mypassword"
RECIPIENT_ADDRESS = PROBLEM HERE (I can only write one to multiple email receivers, but not to iterate by row as the message).
HOST_ADDRESS = 'smtp-mail.outlook.com'
HOST_PORT = 587
# Connection with the server
server = smtplib.SMTP(host=HOST_ADDRESS, port=HOST_PORT)
server.starttls()
server.login(MY_ADDRESS, MY_PASSWORD)
# Creation of the MIMEMultipart Object
message = MIMEMultipart()
# Setup of MIMEMultipart Object Header
message['From'] = MY_ADDRESS
message['To'] = RECIPIENT_ADDRESS
message['Subject'] = "Alerts"
# Creation of a MIMEText Part
textPart = MIMEText(z)
# Part attachment
message.attach(textPart)
# Send Email and close connection
server.send_message(message)
server.quit()
Is there a way to do this? My dataframe has a row which includes the respective receiver email address, but I cant use it. I get the following error: " AttributeError: 'list' object has no attribute 'encode'"
Thanks in advance :)
Best regards,
Solution 1:[1]
I solved this adding the following code:
#This goes inside the previous for loop
for each_line in DataFrame.index:
X = DataFrame['Column'][each_line]
RECIPIENT_ADDRESS = X
print(X)
#Then (inside the for loop)
message['To'] = RECIPIENT_ADDRESS
Hope this work for you too :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
