EmailMultiAlternatives无法建立连接,因为目标计算机主动拒绝了它

时间:2018-11-13 08:28:44

标签: python jquery django

我正在尝试发出ajax请求,以为用户生成密码并向他们发送包含密码的电子邮件。除了我在msg.send()

遇到的错误,所有这些都工作正常

Ajax:

<script type="text/javascript">
        var frm = $('#retrieveKeyForm');

            frm.submit(function (e) {

                e.preventDefault();

                $.ajax({
                    type: frm.attr('method'),
                    url: frm.attr('action'),
                    data: frm.serialize(),
                    success: function (data) {
                        console.log('Submission was successful.');
                    },
                    error: function (data) {
                        console.log('An error occurred.');
                        console.log(data);
                    },
                });
            });
        </script>

Views.py

    class GenerateSecretKey(APIView):
        def get(self, request):
    #Get email address from request
            emailaddr = request.GET.get('email')
            print(emailaddr)
#Show the email address(for debugging)
            min_char = 10
            max_char = 12
            allchar = string.ascii_letters + string.digits
#Generate passsword
            password = "".join(choice(allchar) for x in range(randint(min_char, max_char)))
            print("Your password is {}".format(password))

            subject, from_email, to = 'Your key is ready!', 'test@test.com', emailaddr
            html_content = render_to_string('testapp/email.html', {'password':password})
            text_content = strip_tags(html_content) 
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            return Response({'Success':'Your key has been generated. Please check your email.'})

错误:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

1 个答案:

答案 0 :(得分:0)

此代码块工作得更好。我没有配置SMTP服务器或指定任何SMTP详细信息,所以这就是我收到该错误的原因。特别感谢这个人https://github.com/llamafarmer/email/blob/master/sendEmailAttachment.py

        fromaddr = "test@test.com"    
        toaddr = request.GET.get('email')      
        print(toaddr)
        smtp_user = "test@gmail.com"    
        smtp_pass = "abctest"    
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = "Ready!"    


        body = render_to_string('testapp/email.html', {'password':password})
        msg.attach(MIMEText(body, 'html'))
        server = smtplib.SMTP('in-v3.mailjet.com', 587) 
        server.starttls()
        server.login(smtp_user, smtp_pass)
        text = msg.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
        return Response({'Success':'Your key has been generated. Please check your email.'})