基于 csv 问题发送 Python 多封邮件

Sending multiple Emails with Python based on csv problem

我正在测试 python 发送电子邮件,但我无法从一个 csv 文件发送多封电子邮件。

CSV 文件如下所示

name email
name1 example@gmail.com
name2 another#gmail.com

这是我的代码:

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
login = "joo123456h@gmail.com"
password = input("Type your password and press enter:")

message = """Subject: Order confirmation
To: {recipient}
From: {sender}

Hi {name}, thanks for your order! We are processing it now and will contact you soon"""
sender = "new@example.com"


context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.connect()     
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted    
    server.login(login, password)
with open("contacts.csv") as file:
        reader = csv.reader(file)
        next(reader)  # it skips the header row
        for name, email in reader:
                server.sendmail(
                sender,
                email,
                message.format(name=name, recipient=email, sender=sender)
            )
        print(f'Sent to {name}')

我得到的错误:

SMTPServerDisconnected: please run connect() first

我认为这段代码有问题。

代码:

    server.connect()     
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted    
    server.login(login, password)

完整的代码应该是这样的:

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
login = "joo123456h@gmail.com"
password = input("Type your password and press enter:")

message = """Subject: Order confirmation
To: {recipient}
From: {sender}

Hi {name}, thanks for your order! We are processing it now and will contact you soon"""
sender = "new@example.com"


context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.connect('smtp.gmail.com', '587')
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted   
    server.login(login, password)
    
    with open("contacts.csv") as file:
            reader = csv.reader(file)
            next(reader)  # it skips the header row
            for name, email in reader:
                    server.sendmail(
                    sender,
                    email,
                    message.format(name=name, recipient=email, sender=sender)
                )
            print(f'Sent to {name}')

如果它不起作用请告诉我