微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用python实现电子邮件自动化

如何解决使用python实现电子邮件自动化

我使用 python 自动发送电子邮件,问题是有时代码有效,有时无效。

代码中,python 基本上从 txt 中获取我的联系人,然后在另一个 txt 中获取我的电子邮件消息,并将消息从我的 txt 消息发送到存储在我的 contact.txt 中的联系人。

当问题大部分是我更新mycontacts.txt时出现的错误是:

Traceback (most recent call last):
  File "c:/emailbot/botmessav1.py",line 70,in <module>
    main()
  File "c:/emailbot/botmessav1.py",line 36,in main
    names,emails = get_contacts('mycontacts.txt') # read contacts
  File "c:/emailbot/botmessav1.py",line 21,in get_contacts
    names.append(a_contact.split()[0])
IndexError: list index out of range  ```

以下是联系人列表的示例,mycontacts.txt

marina marinam@gmail.com
luis luis@gmail.com
carlos carlos@gmail.com
marcelo marcelom@gmail.com

这是我正在使用的代码

import smtplib

from string import Template

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

MY_ADDRESS = 'e-mail'
PASSWORD = 'password'

def get_contacts(mycontacts):
    """
    Return two lists names,emails containing names and email addresses
    read from a file specified by filename.
    """
    
    names = []
    emails = []
    with open(mycontacts,mode='r',encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names,emails

def read_template(message):
    """
    Returns a Template object comprising the contents of the 
    file specified by filename.
    """
    
    with open(message,'r',encoding='utf-8') as template_file:
        template_file_content = template_file.read()
    return Template(template_file_content)

def main():
    names,emails = get_contacts('mycontacts.txt') # read contacts
    message_template = read_template('message.txt')

    # 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 name,email in zip(names,emails):
        msg = MIMEMultipart()       # create a message

        # add in the actual person name to the message template
        message = message_template.substitute(PERSON_NAME=name.title())

        # 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']="Subject"
        
        # 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()

解决方法

contacts.txt 文件中不应有任何空行

marina marinam@gmail.com
luis luis@gmail.com
carlos carlos@gmail.com
marcelo marcelom@gmail.com

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。