简体   繁体   English

email 个人如何使用 csv 文件?

[英]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.我对 python 相当陌生,我正在尝试编写一个代码,该代码将采用 csv 文件和 email 一行中的所有电子邮件,同时每次切换名称。 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.问题是,我成功登录,但后来我收到一堆关于文件/系统/库的文本,它给了我错误:TypeError:预期的字符串或缓冲区。 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. message可以是包含 ASCII 范围内的字符的字符串,也可以是字节字符串。 from smtplib.sendmail 来自 smtplib.sendmail

However, in your code, message is a tuple.但是,在您的代码中, message是一个元组。 Convert that to a string, and you should be good to go.将其转换为字符串,您应该对 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?')而不是:message=('Hey', noastrick(nobrackets(names)),'你好吗?')

Perhaps try: message=(f'Hey {noastrick(nobrackets(names))} how are you doing?')也许试试: message=(f'Hey {noastrick(nobrackets(names))} 你好吗?')

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.该建议使用 f 字符串文字来制作一个字符串,其中您的函数结果作为字符串直接插入到字符串中,因此您的消息变量将包含一个字符串而不是元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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