簡體   English   中英

嘗試使用SMTP發送電子郵件時python中出現錯誤

[英]Error in python while trying to send emails using SMTP

我無法在現有問題上找到此錯誤的答案,因此就在這里。 我正在嘗試將電子郵件發送到使用Python,gmail和smtplib庫從CSV文件導入的電子郵件地址列表。 這是代碼:

import smtplib
import csv

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = 'myemailaddress'
PASSWORD = 'mypassword'

def get_contacts(filename):
    """
    Return email addresses read from a file specified by filename.
    """

    emails = []
    with open(filename, newline='') as contacts_file:
        emailreader = csv.reader(contacts_file, delimiter=' ', quotechar='|')
        for a_contact in emailreader:
            emails.append(a_contact)
    return emails


def main():
    emails = get_contacts('mycontacts.csv') # read contacts
    message_template = """Test message goes here"""

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login(MY_ADDRESS, PASSWORD)

    # For each contact, send the email:
    for email in zip(emails):
        msg = MIMEMultipart()       # create a message

        # add in the actual person name to the message template
        message = message_template

        # Prints out the message body for our sake
        print(message)

        # setup the parameters of the message
        msg['From']=MY_ADDRESS
        msg['To']=email
        msg['Subject']="This is TEST"

        # add in the message body
        msg.attach(MIMEText(message, 'plain'))

        # send the message via the server set up earlier.
        s.send_message(msg)
        del msg

    # Terminate the SMTP session and close the connection
    s.quit()

if __name__ == '__main__':
    main()

我收到以下錯誤:

Traceback (most recent call last):
  File "py_mail.py", line 58, in <module>
    main()
  File "py_mail.py", line 51, in main
    s.send_message(msg)
  File "/home/hugo/anaconda3/lib/python3.7/smtplib.py", line 942, in send_message
    to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
  File "/home/hugo/anaconda3/lib/python3.7/email/utils.py", line 112, in getaddresses
    all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, tuple found

在我看來,嘗試從電子郵件列表中讀取電子郵件時發生了錯誤,但老實說我無法弄清楚。 歡迎任何幫助或指向相關答案的鏈接。

更新:我使用的是zip,因為這是原始腳本所做的( https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f )。 刪除錯誤后,錯誤消失了,但是出現了一個新錯誤: TypeError: sequence item 0: expected str instance, list found現在我唯一的問題是如何將我的電子郵件列表更改為smtplib可接受的輸入

您必須將for email in zip(emails)for email in emails更改for email in emails

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM