本文整理匯總了Python中django.core.mail.EmailMessage方法的典型用法代碼示例。如果您正苦於以下問題:Python mail.EmailMessage方法的具體用法?Python mail.EmailMessage怎麽用?Python mail.EmailMessage使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.core.mail
的用法示例。
在下文中一共展示了mail.EmailMessage方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: send_receipts
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_receipts(invoice, email, amount):
name = invoice.client_full_name
id = invoice.id
# Administrator successful payment receipt
admin_receipt_message = render_to_string(
'emails/admin_receipt.txt', {
'email': email,
'name': name,
'amount': amount,
'id': id,
})
admin_receipt = EmailMessage(
name +
" has successfully paid",
admin_receipt_message,
email,
[email])
admin_receipt.content_subtype = 'html'
admin_receipt.send()
示例2: handle
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def handle(self, *args, **options):
email = options["email"]
last_days = options["last_days"]
# today is excluded
end = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
start = end - timedelta(days=last_days)
employments = Employment.objects.filter(updated__range=[start, end])
if employments.exists():
from_email = settings.DEFAULT_FROM_EMAIL
subject = "[Timed] Employments changed in last {0} days".format(last_days)
body = template.render({"employments": employments})
message = EmailMessage(
subject=subject,
body=body,
from_email=from_email,
to=[email],
headers=settings.EMAIL_EXTRA_HEADERS,
)
message.send()
示例3: contact
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def contact(request):
emailForm = EmailForm(request.POST)
if emailForm.is_valid():
subject = '[BikeMaps] '+ emailForm.cleaned_data['subject']
message = emailForm.cleaned_data['message']
sender = emailForm.cleaned_data['sender']
cc_myself = emailForm.cleaned_data['cc_myself']
recipients = ['admin@bikemaps.org','tech-support@bikemaps.org']
cc = [sender] if cc_myself else []
email = EmailMessage(subject, message, 'admin@bikemaps.org', recipients, headers = {'Reply-To': sender}, cc = cc)
try:
email.send()
messages.success(request, '<strong>' + _('Thank you!') + '</strong><br>' + _('We\'ll do our best to get back to you soon.'))
emailForm = EmailForm() # Clear the form
except BadHeaderError:
messages.error(request, '<strong>'+ _('Invalid Header.') + '</strong>' + _('Illegal characters found.'))
return render(request, 'mapApp/about.html', {"emailForm": emailForm})
示例4: sender
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def sender(request, subject, template_name, context, to):
site = get_current_site(request)
context.update({'site_name': site.name,
'domain': site.domain,
'protocol': 'https' if request.is_secure() else 'http'})
message = render_to_string(template_name, context)
from_email = "%(site_name)s <%(name)s@%(domain)s>" % {'name': "noreply",
'domain': site.domain,
'site_name': site.name}
if len(to) > 1:
kwargs = {'bcc': to, }
else:
kwargs = {'to': to, }
email = EmailMessage(subject, message, from_email, **kwargs)
try:
email.send()
except SMTPException as err:
logger.error(err)
示例5: test_send_comment
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def test_send_comment(self):
data = {
"send_to": "cornerwise",
"subject": "Hello",
"comment": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}
response = self.client.post(reverse("contact-us"), data)
self.assertEqual(response.status_code, 200)
comment = models.UserComment.objects.order_by("-created")[0]
self.assertEqual(comment.subject, data["subject"])
self.assertEqual(comment.comment, data["comment"])
self.assertEqual(len(mail.outbox), 1)
message: mail.EmailMessage = mail.outbox[0]
self.assertIn(self.admin.email, message.recipients())
html = message.substitutions["-message_html-"]
self.assertIn("Hello", html)
示例6: handle
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def handle(self, *args, **options):
providerEmails = []
#all action items that are past due and incomplete
actionItemList = models.ActionItem.objects.filter(due_date__lte=django.utils.timezone.now().date()).filter(completion_date=None)
for actionItem in actionItemList:
try:
for coordinator in actionItem.patient.case_managers.all():
email = coordinator.associated_user.email
if email not in providerEmails:
providerEmails = providerEmails + [email]
except AttributeError:
pass
message = '''Hello Case Manager! You have an action item due. Please do it otherwise you will
continue to be spammed. Thanks! If you are recieving this message but you really don't have
an action item due, please contact your current Tech Tsar to relieve you of your misery.'''
email = EmailMessage('SNHC: Action Item Due', message, to=providerEmails)
email.send()
示例7: test_asm
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def test_asm(self):
msg = EmailMessage(
subject="Hello, World!",
body="Hello, World!",
from_email="Sam Smith <sam.smith@example.com>",
to=["John Doe <john.doe@example.com>", "jane.doe@example.com"],
)
msg.asm = {"group_id": 1}
result = self.backend._build_sg_mail(msg)
self.assertIn("asm", result)
self.assertIn("group_id", result["asm"])
del msg.asm["group_id"]
with self.assertRaises(KeyError):
self.backend._build_sg_mail(msg)
msg.asm = {"group_id": 1, "groups_to_display": [2, 3, 4], "bad_key": None}
result = self.backend._build_sg_mail(msg)
self.assertIn("asm", result)
self.assertIn("group_id", result["asm"])
self.assertIn("groups_to_display", result["asm"])
示例8: send_order_email_confirmation
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_order_email_confirmation(sender, instance, **kwargs):
"""
Send email to customer with order details.
"""
order = instance
message = get_template("emails/order_conf.html").render(Context({
'order': order.get_serialized_data()
}))
mail = EmailMessage(
subject="Order confirmation",
body=message,
from_email=EMAIL_ADMIN,
to=[order.email],
reply_to=[EMAIL_ADMIN],
)
mail.content_subtype = "html"
return mail.send()
示例9: send_email_messages
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_email_messages(self, recipient, messages, site=None): # pylint:disable=arguments-differ
"""
Plain email sending to the specified recipient
"""
from_email = settings.OSCAR_FROM_EMAIL
if site:
from_email = site.siteconfiguration.get_from_email()
# Determine whether we are sending a HTML version too
if messages['html']:
email = EmailMultiAlternatives(messages['subject'],
messages['body'],
from_email=from_email,
to=[recipient])
email.attach_alternative(messages['html'], "text/html")
else:
email = EmailMessage(messages['subject'],
messages['body'],
from_email=from_email,
to=[recipient])
self.logger.info("Sending email to %s", recipient)
email.send()
return email
示例10: _build_message
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def _build_message(self, rcpt, total, reqs):
"""Build new EmailMessage instance."""
if self.options["verbose"]:
print("Sending notification to %s" % rcpt)
context = {
"total": total,
"requests": reqs,
"baseurl": self.baseurl,
"listingurl": self.listingurl
}
content = render_to_string(
"modoboa_amavis/notifications/pending_requests.html",
context
)
msg = mail.EmailMessage(
_("[modoboa] Pending release requests"),
content,
self.sender,
[rcpt]
)
return msg
示例11: send_mail_task
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_mail_task(**kwargs):
response = {'status': '', 'id': None}
email = EmailMessage(**kwargs)
try:
email.send()
except Exception as e:
response['status'] = 'Error: ' + str(e)
else:
try:
return {
'status': email.anymail_status.status.pop(),
'id': email.anymail_status.message_id,
}
except AttributeError:
response['status'] = 'sent'
return response
示例12: send_redirect_report
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_redirect_report(bad_redirects):
msg = 'The Openstax Redirect Report has been run'
msg += '\n\nShort Code,Redirect URL'
msg += '\n' + str(bad_redirects)
subject = 'OpenStax Redirect Report'
from_address = 'noreply@openstax.org'
to_address = ['cmsupport@openstax.org', ]
try:
email = EmailMessage(subject,
msg,
from_address,
to_address)
email.send()
except Exception as e:
logger.error("EMAIL FAILED TO SEND: subject:{}".format(subject))
示例13: mass_mail_sending_view
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def mass_mail_sending_view(request):
m1 = mail.EmailMessage(
'First Test message',
'This is the first test email',
'from@example.com',
['first@example.com', 'second@example.com'])
m2 = mail.EmailMessage(
'Second Test message',
'This is the second test email',
'from@example.com',
['second@example.com', 'third@example.com'])
c = mail.get_connection()
c.send_messages([m1, m2])
return HttpResponse("Mail sent")
示例14: send_contact_email
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_contact_email(self):
"""
Send contact email to the student and CC instructor
"""
body = wrap(self.substitite_values(self.contact_email_text), 72)
email = EmailMessage(
subject='Academic dishonesty in %s' % (self.get_origsection()),
body=body,
from_email=self.owner.email(),
to=[self.student.email()],
cc=[self.owner.email()],
)
email.send(fail_silently=False)
示例15: send_invoice
# 需要導入模塊: from django.core import mail [as 別名]
# 或者: from django.core.mail import EmailMessage [as 別名]
def send_invoice(request, invoice, admin=False):
# Set Variables
admin_email_address = settings.ADMIN_EMAIL
link = request.build_absolute_uri(invoice.url())
id = str(invoice.id)
def admin_email():
adminmessage = render_to_string(settings.ADMIN_INVOICE_MESSAGE_TEMPLATE_PATH, {
'invoice': invoice,
'link': link,
})
# Email to business owner
admin_email = EmailMessage(
'Invoice #' + id,
adminmessage,
admin_email_address,
[admin_email_address])
admin_email.content_subtype = "html"
admin_email.send()
# Customer Email
def customer_email():
invoicemessage = render_to_string(settings.CLIENT_INVOICE_MESSAGE_TEMPLATE_PATH, {
'invoice': invoice,
'link': link,
})
customer_email = EmailMessage('Invoice #' + id, invoicemessage, admin_email_address, [invoice.email])
customer_email.content_subtype = "html"
customer_email.send(fail_silently=False)
customer_email()
if admin is True:
admin_email()