Python smtplib 向对应行中的收件人发送电子邮件

Posted

技术标签:

【中文标题】Python smtplib 向对应行中的收件人发送电子邮件【英文标题】:Python smtplib send email to recipient in correspondant row 【发布时间】:2022-01-11 22:55:33 【问题描述】:

有没有办法使用 python smtplib 发送邮件,其收件人在数据框中的行不同? (一对一邮件) 我可以逐行发送不同的消息,但我不能与接收者复制相同的消息,因为我只能将它们发送给一个或我提到的所有接收者。我无法将它发送到相应行的接收器。我有以下代码:

for each_line in df.index:
    z = message (its an example... this part is like df['first column'] + " hello " + df['second column'])
    MY_ADDRESS = "mymail@mail.com" 
    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()

有没有办法做到这一点? 我的数据框有一行包含相应的接收者电子邮件地址,但我无法使用它。我收到以下错误: " AttributeError: 'list' 对象没有属性 'encode'"

提前致谢:)

最好的问候,

【问题讨论】:

【参考方案1】:

我通过添加以下代码解决了这个问题:

li = DataFrame['Column'].values.tolist() 
length = len(li)  

#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

希望这对你也有用:)

【讨论】:

以上是关于Python smtplib 向对应行中的收件人发送电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

python发邮件

使用 Python smtplib 从 .txt 文件向多个收件人发送电子邮件

定时发送邮件

python 发邮件

python smtplib发送邮件

python smtplib发送邮件