在这里我有一个视图,该视图将向选定的用户发送电子邮件或删除选定的用户。删除选定的用户工作正常,但向选定的用户发送电子邮件却无法正常工作。我尝试了这些方法将电子邮件发送到选定的电子邮件。 第一种方法
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'email'
如果电子邮件发送给用户,我也想从会话中删除选定的用户,然后重新启动会话,这在此代码中不会发生
第二种方法是说invalid email address
。
第一种方法
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')
第二种方法
模板
<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
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
class SendMailForm(forms.Form):
to = forms.EmailField(required=False)
sub = forms.CharField(max_length=250)
msg = forms.CharField(widget=forms.Textarea)
答案 0 :(得分:1)
您已将电子邮件地址而非用户对象存储在列表中。因此,您应该直接使用它们:
for email in request.session['users']:
email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[email], connection=backend)