简体   繁体   中英

Trying to send emails from python using smtplib and email.mime.multipart, getting the error “'Series' object has no attribute 'encode'”

I am trying to make a streamlit app that takes an excel sheet as input file saves it as a working file and then send mails to the stored email addresses. I am getting this error : AttributeError: 'Series' object has no attribute 'encode'

here's the code:

import streamlit as st
import pandas as pd 
import numpy as np 
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib,ssl

st.title("BD Triggers-Lead Generator Mail")
#uploaded_file = st.file_uploader("Choose a file")
temp_file = st.file_uploader("Enter file here!")
if temp_file: 
    temp_file_contents = temp_file.read()

if st.button("Save as working file"):
    with open("ON_DISK_FILE.extension","wb") as file_handle:
        file_handle.write(temp_file_contents)


result= st.button('Click To Send Mail')
st.write(result)
if result:

    my_email= "example@gmail.com"
    password= "abc@123"



    server = smtplib.SMTP_SSL('smtp.gmail.com' ,465)
    server.ehlo()
    server.login(my_email, password)
    email_list = pd.read_excel("ON_DISK_FILE.extension") 
    st.write(email_list)
 

 
    #defining objects
    names = email_list['Lead Generated']
    emails = email_list['Lead generator Email']
    subjects = email_list["Subject"]    
    ccs=email_list['CCs']

    for i in range(len(emails)):
        name=names[i]
        email=emails[i]
        subject=subjects[i]
        cc=ccs[i]

        msg=MIMEMultipart()
        msg['Subject']=subjects
        msg['From']=my_email
        msg["To"]=email
        msg["Cc"]=cc
        text="Hi"

        part1 = MIMEText(text, "plain")
        msg.attach(part1)
        
        server.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
    
    server.close()

This is the traceback:

    File "c:\users\dell\anaconda3\lib\site-packages\streamlit\script_runner.py", line 338, in _run_script
    exec(code, module.__dict__)
File "C:\Users\DELL\Desktop\bdmail.py", line 81, in <module>
    server.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
File "c:\users\dell\anaconda3\lib\email\message.py", line 158, in as_string
    g.flatten(self, unixfrom=unixfrom)
File "c:\users\dell\anaconda3\lib\email\generator.py", line 116, in flatten
    self._write(msg)
File "c:\users\dell\anaconda3\lib\email\generator.py", line 195, in _write
    # Write the headers.  First we see if the message object wants to
File "c:\users\dell\anaconda3\lib\email\generator.py", line 222, in _write_headers
    #
File "c:\users\dell\anaconda3\lib\email\_policybase.py", line 326, in fold
    return self._fold(name, value, sanitize=True)
File "c:\users\dell\anaconda3\lib\email\_policybase.py", line 369, in _fold
    parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen))
File "c:\users\dell\anaconda3\lib\site-packages\pandas\core\generic.py", line 5274, in __getattr__

I am not able to fix the error, can someone please help me with this!

The error message is a hint here: it says that you are attempting to process a pandas Series in that line:

server.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())

It means that when composing your message, you have written a raw Series somewhere. The culprit is here:

msg['Subject']=subjects      # subjects is the full pandas column, ie a Series

The full problem was caused by a typo: you wanted probably:

msg['Subject']=subject

What to learn from that:

  • you have set up the trap where your have fallen, by using the same variable in singular and plural form to avoid handling indices forms ( subject for subjects[i] ). There is nothing bad per se, but it requires to be very cautious.
  • Python error messages often carry a lot of information provided you try to understand them : the line raising the error, and often information about the type or content of the offending variables (here a Pandas Series was involved)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM