from django.template import loader, Context
from django.core.mail import EmailMultiAlternatives, EmailMessage
from settings import ADBOARD_SETTINGS
import settings
def send_mail(mail_to, subj, message_dict, template_dict=False, mail_from=ADBOARD_SETTINGS['mail_from'], attach=False):
if not isinstance(mail_to, list):
mail_to = [mail_to]
if template_dict:
txt = loader.get_template(template_dict['txt'])
html = loader.get_template(template_dict['html'])
c = Context(message_dict or None)
message_txt = txt.render(c)
message_html = html.render(c)
msg = EmailMultiAlternatives(subj, message_txt, mail_from, mail_to)
msg.attach_alternative(message_html, "text/html")
else:
msg = EmailMessage(subj, message_dict, mail_from, mail_to)
if attach:
for one in attach:
msg.attach(one[0], one[1], one[2])
msg.send()
def contacts(request):
from choices import ContactCategoryChoices
if request.method == 'POST':
form = ContactForm(request.POST, request.FILES)
if form.is_valid():
data = {
'email': form.cleaned_data.get('email'),
'subject': form.cleaned_data.get('subject'),
'message': form.cleaned_data.get('message'),
'category': int(form.cleaned_data.get('category'))
}
recievers = (
(#recievers)
emailList = list(dict(recievers)[data.get('category')])
attaches = [(upload.name, upload.read(), upload.content_type) for upload in
[form.cleaned_data[attach] for attach in request.FILES]]
send_mail(emailList, u'Письмо со страницы контактов', data, {
'txt': 'home/contacts/txt.html',
'html': 'home/contacts/html.html',
}, mail_from=settings.SENDER_EMAIL, attach=attaches)
messages.add_message(request, messages.SUCCESS, u'Сообщение отправлено')
form = ContactForm()
else:
form = ContactForm()
return render_to_response('home/contacts/index.html', {'form': form}, context_instance=RequestContext(request))
如果我添加一些文件 - 它们在附件中显示为“无名”……不仅是 gmail。Django 1.3.1,utf-8 命名文件。有没有机会在不转换为 ascii 的情况下使其工作?只要由于保存原始文件名而无法转换它就非常重要。
更新:
同时标题似乎合法: