简体   繁体   English

如何向选定的用户发送邮件

[英]How to send mail to selected users

Here i have a view which will either sends email to selected users or delete the selected users.The deleting the selected users is working fine but sending email to selected to users is not working.在这里,我有一个视图,它将向选定的用户发送 email 或删除选定的用户。删除选定的用户工作正常,但将 email 发送给选定的用户不起作用。 I tried these ways for sending email to selected email.我尝试了这些方法将 email 发送到选定的 email。 with first approach第一种方法

Exception Type: AttributeError
Exception Value:    
'str' object has no attribute 'email'

and also i want to remove the selected users from session if email sends to the users and restart the session again which is not happening here with this code我还想从 session 中删除选定的用户,如果 email 发送给用户并重新启动 session 再次使用此代码

With second approach it says invalid email address .使用第二种方法,它说invalid email address

First Approach第一种方法

def selected_users(request):
    selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users'))

#tring to store selected users in session
    initial = {'users':[]}
    session = request.session.get('users',initial)
    if selected_users:
        for user in selected_users:
            session['users'].append(user.email)
            request.session['users'] = session
            print('hello',request.session['users']) # here i want to restart session either email sends or not to the user
    if selected_users and  request.method == 'POST' and 'delete_selected' in request.POST:
            selected_users.delete()
            messages.success(request, 'deleted')
            return redirect('view_users')
    elif request.method == 'POST' and 'mail_selected' in request.POST:
            form = SendMailForm(request.POST or None)
            config = EmailConfiguration.objects.order_by('-date').first()
            backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user,
                                   password=config.email_host_password, use_tls=config.email_use_tls)
            if form.is_valid():
                sub = form.cleaned_data['sub']
                msg = form.cleaned_data['msg']
                for user in request.session['users']:
                    email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[user.email],
                                             connection=backend)
                    email.send()
                    messages.success(request, 'Your mail sent.')
                    return redirect('view_users')

            return render(request, 'send_mail_selected.html', {'users': selected_users,'form':form})

    else:
            messages.error(request, 'Invalid request')
            return redirect('view_users')

second approach第二种方法

template模板

<form method="POST" >
    {% csrf_token %}
<p><label>To</label> <input type="text" value="{% for user in users %}{{user.email}}{% endfor %}"></p>

<p><label>Subject</label> <input type="text" name="sub" ></p>
<p><label>Message</label> <textarea name="msg" rows="10"></textarea></p>
<button type="submit" class="btn btn-primary" name="mail_selected">Send </button>

</form>

views.py视图.py

            if form.is_valid():
                sub = form.cleaned_data['sub']
                msg = form.cleaned_data['msg']
                to = form.cleaned_data['to']
                email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=to,
                                             connection=backend)
                email.send()
                messages.success(request, 'Your mail sent.')
                return redirect('view_users')

            return render(request, 'send_mail_selected.html', {'users': selected_users,'form':form})

forms.py forms.py

class SendMailForm(forms.Form):
    to = forms.EmailField(required=False)
    sub = forms.CharField(max_length=250)
    msg = forms.CharField(widget=forms.Textarea)

You've stored the email addresses, not the user objects, in the list.您已在列表中存储了 email 地址,而不是用户对象。 So you should use them directly:所以你应该直接使用它们:

for email in request.session['users']:
    email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[email], connection=backend)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM