简体   繁体   中英

How do I email individuals with csv files?

I am fairly new to python, and I am trying to write a code that will take a csv file and email all the emails in one row, while switching the names each time. Here is what I wrote:

import smtplib
import csv

def nobrackets(current):
    return str(current).replace('[','').replace(']','')
def noastrick(current):
    return str(current).replace('\'','').replace('\'','')

sender_email = "xxxxxxxxx"

password = "xxxxxxxxx"

names=[]
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
print("Login success")
with open('Emails.csv','r') as csv_file:
    csv_reader=csv.reader(csv_file)
    for line in csv_reader:
        names.append(line[0])
        message=('Hey', noastrick(nobrackets(names)),'how are you doing?')
        server.sendmail(sender_email, line, message)
        names.clear()

The problem is, I get logged in successfully, but then I get a bunch of text about File/System/Library things and it gives me the error: TypeError: expected string or buffer. Anyone know what is going on?

When using

server.sendmail(sender_email, line, message)

message may be a string containing characters in the ASCII range, or a byte string. from smtplib.sendmail

However, in your code, message is a tuple. Convert that to a string, and you should be good to go. For example:

server.sendmail(sender_email, line, " ".join(message))

It might be helpful if you post the entire error message. That being said, just as a guess, it could be related to your message string - it looks like you're passing a tuple as your message rather than a string.

Instead of: message=('Hey', noastrick(nobrackets(names)),'how are you doing?')

Perhaps try: message=(f'Hey {noastrick(nobrackets(names))} how are you doing?')

The suggestion uses an f string literal to make one string with the results of your functions inserted directly into the string as a string, so your message variable will contain a string and not a tuple.

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