发送电子邮件时字符串索引超出范围

时间:2016-09-23 16:01:13

标签: python django email

我在尝试使用Django EmailMultiAlternatives发送邮件时遇到此错误:link。我尝试搜索此错误但没有运气,我也尝试删除或更改电子邮件的每个变量,但没有运气。

这是代码:

def spremembapodatkovproc(request):
    if request.method == 'POST':
        req_id = request.POST.get('req_num', 'Neznan ID zahtevka')
        old_email = request.user.email
        old_name = request.user.get_full_name
        new_email = request.POST.get('email_new', 'Nov e-mail ni znan')
        new_fname = request.POST.get('fname_new', 'Novo ime ni znano')
        dokument = request.FILES.get('doc_file')
        komentar = request.POST.get('comment', 'Ni komentarja')
        # try:
        plaintext = get_template('email/usr-data-change.txt')
        htmly = get_template('email/usr-data-change.html')

        d = Context(
            {
                'old_email': old_email,
                'old_fname': old_name,
                'new_email': new_email,
                'new_fname': new_fname,
                'req_id': req_id,
                'komentar': komentar,
                'user_ip': request.META.get('REMOTE_ADDR', 'IP Naslova ni mogoče pridobiti.')
            }
        )

        subject, from_email, to = 'eBlagajna Sprememba podatkov', 'eblagajna@ksoft.si', ["info@korenc.eu"]
        text_content = plaintext.render(d)
        html_content = htmly.render(d)
        print(text_content)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")

        msg.mixed_subtype = 'related'

        for f in ["templates\\email\\img1.png"]:
            fp = open(os.path.join(BASE_DIR, f), 'rb')
            msg_img = MIMEImage(fp.read())
            fp.close()
            msg_img.add_header('Content-ID', '<{}>'.format(f))
            msg.attach(msg_img)
        msg.send()

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

问题在于另一个列表中的电子邮件冗余包装列表。

基本上是变量to = ["info@korenc.eu"],然后是行运行

msg = EmailMultiAlternatives(subject, text_content, from_email, [to])

它用to括号再次包裹[ ]。和[to] = [["info@korenc.eu"]],但它应该是简单的列表。所以通过将问题行更改为

msg = EmailMultiAlternatives(subject, text_content, from_email, to)
一切顺利。