2016-09-23 73 views
0

我遇到了此錯誤:link,同時嘗試使用Django EmailMultiAlternatives發送郵件。我試圖尋找這個錯誤,但沒有運氣,我也嘗試刪除或更改每個變量的電子郵件,但沒有運氣。發送電子郵件時,字符串索引超出範圍

這是代碼:

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', '[email protected]', ["[email protected]"] 
     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() 

謝謝您的幫助。

+0

你有'to = [「[email protected]」]',並且你試圖在初始化'EmailMultiAlternatives'實例的時候把它包裝在'[]'括號中。嘗試將'EmailMultiAlternatives(subject,text_content,from_email,[to])'改爲'EmailMultiAlternatives(subject,text_content,from_email,to)' –

+0

謝謝!有用。 – AndyTemple

回答

3

問題在於電子郵件的冗餘包裝列表在另一個列表中。

所以基本上可變to = ["[email protected]"],然後當線運行

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

它包裹to一個更多的時間與[ ]括號。和[to] = [["[email protected]"]],但它應該是簡單的列表。所以通過更改問題行到

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

一切正常。

相關問題