我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.core.mail.EmailMultiAlternatives()。
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Sends a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send()
def __init__(self, to, subject, template, render_context={}): if not isinstance(to, list): to = [to] render_context.update({'application_message_recipient': to[0]}) self.render_context = render_context body = render_to_string(template, render_context) # Use max line length from RFC2822 (78) instead of RFC5322 (998) # to force conversion to quoted-printable in almost all cases django.core.mail.message.RFC5322_EMAIL_LINE_LENGTH_LIMIT = 78 self.msg = EmailMultiAlternatives( subject=subject, body=body, to=to, from_email=self.message_from, headers={ 'Auto-Submitted': 'auto-generated', 'Return-Path': settings.SERVICE_MSG_RETURN_PATH, 'Message-ID': mk_msgid() }, )
def send_email(to, kind, **kwargs): current_site = Site.objects.get_current() ctx = { "current_site": current_site, "STATIC_URL": settings.STATIC_URL, } ctx.update(kwargs.get("context", {})) subject = "[%s] %s" % ( current_site.name, render_to_string("emails/%s/subject.txt" % kind, ctx).strip() ) message_html = render_to_string("emails/%s/message.html" % kind, ctx) message_plaintext = strip_tags(message_html) from_email = settings.DEFAULT_FROM_EMAIL email = EmailMultiAlternatives(subject, message_plaintext, from_email, to) email.attach_alternative(message_html, "text/html") email.send()
def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None, headers=None, cc=None, bcc=None): """Override django send_mail function to allow use of custom email headers. """ connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection, headers=headers, cc=cc, bcc=bcc) if html_message: mail.attach_alternative(html_message, 'text/html') return mail.send()
def send(self): """Sends the payment email along with the invoice.""" body = self.get_body() # Set non-empty body according to # http://stackoverflow.com/questions/14580176/confusion-with-sending-email-in-django mail = EmailMultiAlternatives(subject=self.get_subject(), body=strip_tags(body), to=self.get_recipient_list(), cc=self.get_cc_list(), bcc=self.get_bcc_list()) mail.attach_alternative(body, 'text/html') for attachment in self.attachments: mail.attach_file(attachment[0], attachment[1]) return mail.send()
def send_email_ticket_confirm(request, payment_info): """ :param request Django request object :param payment_info Registration object """ mail_title = u"PyCon APAC 2016 ???? ??(Registration confirmation)" product = Product() variables = Context({ 'request': request, 'payment_info': payment_info, 'amount': product.price }) html = get_template('mail/ticket_registered_html.html').render(variables) text = get_template('mail/ticket_registered_text.html').render(variables) msg = EmailMultiAlternatives( mail_title, text, settings.EMAIL_SENDER, [payment_info.email]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=False)
def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None, connection=None): """ Given a datatuple of (subject, text_content, html_content, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. """ connection = connection or get_connection( username=user, password=password, fail_silently=fail_silently) messages = [] for subject, text, html, from_email, recipient in datatuple: message = EmailMultiAlternatives(subject, text, from_email, recipient) message.attach_alternative(html, 'text/html') messages.append(message) return connection.send_messages(messages)
def post(self, request, pk): user = User.objects.get(id=pk) sign = hashlib.md5(user.email + settings.SECRET_KEY).hexdigest() url = urlparse.ParseResult( scheme=request.scheme, netloc=urlparse.urlparse(request.get_raw_uri()).netloc, path=reverse(('core:SetPassword')), params='', query = urllib.urlencode({'email': user.email, 'sign': sign}), fragment='', ).geturl() msg = EmailMultiAlternatives( subject='??????', body=get_template('users/user_email_activate.html').render({'url': url}), from_email=settings.EMAIL_HOST_USER, to=[user.email,], ) msg.content_subtype = 'html' status = msg.send(fail_silently=True) response = '??????' if status else '??????, ???' return HttpResponse(response)
def mail_send_task(to: str, subject: str, body: str, html: str, sender: str, event: int=None, cc: list=None, bcc: list=None, headers: dict=None): headers = headers or dict() if event: event = Event.objects.get(id=event) sender = sender or event.settings.get('mail_from') headers['reply-to'] = headers.get('reply-to', event.settings.get('mail_from')) backend = event.get_mail_backend() else: backend = get_connection(fail_silently=False) email = EmailMultiAlternatives(subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers) if html is not None: email.attach_alternative(inline_css(html), 'text/html') try: backend.send_messages([email]) except Exception: logger.exception('Error sending email') raise SendMailException('Failed to send an email to {}.'.format(to))
def send_activation_email(request, user): subject = _('Profile Activation') from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) domain = current_site.domain code = get_random_string(20) context = { 'domain': domain, 'code': code, } act = Activation() act.code = code act.user = user act.save() html_content = render_to_string('email/activation_profile.html', context=context, request=request) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_activation_change_email(request, user, new_email): subject = _('Change email') from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) domain = current_site.domain code = get_random_string(20) context = { 'domain': domain, 'code': code, } act = Activation() act.code = code act.user = user act.email = new_email act.save() html_content = render_to_string('email/change_email.html', context=context, request=request) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_reset_password_email(request, user): from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain token_generator = default_token_generator use_https = request.is_secure() context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } subject = loader.render_to_string('registration/password_reset_subject.txt', context) subject = ''.join(subject.splitlines()) body = loader.render_to_string('registration/password_reset_email.html', context) email_message = EmailMultiAlternatives(subject, body, from_email, [user.email]) email_message.send()
def create_mail(subject, message, from_email, recipient, message_html=None, attachments=None, rfc2822_headers=None): headers = {'Message-ID': make_msgid()} if rfc2822_headers: headers.update(rfc2822_headers) if message is None: # make text version out of html if text version is missing message = html2text(message_html) if message_html: msg = EmailMultiAlternatives(subject, message, from_email, [recipient], headers=headers) msg.attach_alternative(message_html, "text/html") else: msg = EmailMessage(subject, message, from_email, [recipient], headers=headers) if attachments: for filename, content, mimetype in attachments: msg.attach(filename, content, mimetype) return msg
def send_code(email, fieldsetup): # create code and expiration time context = dict(fieldsetup.mail_context) context['code'] = (get_code(email, fieldsetup) or str(randint(10 ** (fieldsetup.code_length - 1), 10 ** fieldsetup.code_length - 1))) context['expiration_time'] = now() + timedelta(0, fieldsetup.code_ttl) # store code and expiration time in cache cache.set(fieldsetup.cache_prefix + email, (context['expiration_time'], context['code'])) # create message msg = EmailMultiAlternatives( subject=fieldsetup.mail_subject, body=get_template(fieldsetup.mail_template_txt).render(context), from_email=fieldsetup.mail_from, to=[email], headers={'X-Mailer': fieldsetup.mail_mailer}, ) msg.attach_alternative(get_template(fieldsetup.mail_template_html).render(context), 'text/html') msg.send()
def message(self): if not self._message: if self.drip_base.from_email_name: from_ = "%s <%s>" % (self.drip_base.from_email_name, self.drip_base.from_email) else: from_ = self.drip_base.from_email to_address = [self.context['email_address']] if not isinstance(self.context['email_address'], list) else self.context['email_address'] self._message = EmailMultiAlternatives(self.subject, self.plain, from_, to_address) # check if there are html tags in the rendered template if len(self.plain) != len(self.body): html_body = self.body if self.drip_base.template: html_body = render_to_string(self.drip_base.template, dict(self._data, **{'email_content': html_body})) self._message.attach_alternative(html_body, 'text/html') return self._message
def email_watchers(sender, instance=None, **kwargs): c = { 'ticket': instance.action_object, 'actor': instance.actor, 'verb': instance.verb } if hasattr(instance, 'description') and instance.description != '': c['comment'] = instance.description html_content = get_template('email/html/comment.html').render(c) text_content = '' else: html_content = get_template('email/html/transition.html').render(c) text_content = get_template('email/text/transition.txt').render(c) msg = EmailMultiAlternatives( 'Ticket Tracking System: ' + instance.action_object.key, text_content, settings.EMAIL_ADDRESS, [u.email for u in instance.action_object.watching()]) msg.attach_alternative(html_content, 'text/html') msg.send()
def send_confirmation_email(sender, email, user=None, **kwargs): user = user or sender # TODO: use user.send_email if user is not None: context = { 'email': email, 'domain': settings.BASE_URL, 'site_name': settings.WAGTAIL_SITE_NAME, 'token': user.get_confirmation_key(email), 'new_user': user.get_confirmed_emails() == [] } subject = loader.render_to_string( 'members/email_change_subject.txt', context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string('members/email_change_email.html', context) email_message = EmailMultiAlternatives(subject, body, None, [email]) email_message.send()
def notify_admin_of_invite_request(request_invite): plaintext = get_template('email-invite-request-received.txt') htmly = get_template('email-invite-request-received.html') context = {"APPLICATION_TITLE": settings.APPLICATION_TITLE, "EMAIL": request_invite.email, "FIRST_NAME": request_invite.first_name, "LAST_NAME": request_invite.last_name, "USER_TYPE": request_invite.user_type } subject = '[%s] Request for %s access from : %s %s' % (settings.APPLICATION_TITLE, request_invite.user_type, request_invite.first_name, request_invite.last_name) from_email = settings.DEFAULT_FROM_EMAIL if settings.DEFAULT_FROM_EMAIL == settings.DEFAULT_ADMIN_EMAIL: to_email = [settings.DEFAULT_ADMIN_EMAIL] else: to_email = [settings.DEFAULT_ADMIN_EMAIL, settings.DEFAULT_FROM_EMAIL] text_content = plaintext.render(context) html_content = htmly.render(context) msg = EmailMultiAlternatives(subject, text_content, from_email, to_email) msg.attach_alternative(html_content, "text/html") msg.send()
def send_invite_to_create_account(invitation): plaintext = get_template('email-invite.txt') htmly = get_template('email-invite.html') context = {"APPLICATION_TITLE": settings.APPLICATION_TITLE, "CODE": invitation.code, "URL": invitation.url(), "EMAIL": invitation.email, } subject = '[%s] Invitation Code: %s' % (settings.APPLICATION_TITLE, invitation.code) from_email = settings.DEFAULT_FROM_EMAIL to_email = invitation.email text_content = plaintext.render(context) html_content = htmly.render(context) msg = EmailMultiAlternatives( subject, text_content, from_email, [ to_email, ]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_invitation_code_to_user(user_code_invitation): plaintext = get_template('email-user-code-by-email.txt') htmly = get_template('email-user-code-by-email.html') context = {"APPLICATION_TITLE": settings.APPLICATION_TITLE, "CODE": user_code_invitation.code, "URL": user_code_invitation.url(), "EMAIL": user_code_invitation.email} subject = '[%s] Invitation Code: %s' % (settings.APPLICATION_TITLE, user_code_invitation.code) from_email = settings.DEFAULT_FROM_EMAIL to_email = user_code_invitation.email text_content = plaintext.render(context) html_content = htmly.render(context) msg = EmailMultiAlternatives( subject, text_content, from_email, [ to_email, ]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_password_reset_url_via_email(user, reset_key): plaintext = get_template('email-password-reset-link.txt') htmly = get_template('email-password-reset-link.html') subject = '[%s] Link to reset your password' % (settings.APPLICATION_TITLE) from_email = settings.DEFAULT_FROM_EMAIL to_email = user.email password_reset_link = '%s%s' % (get_hostname(), reverse('password_reset_email_verify', args=(reset_key,))) context = {"APPLICATION_TITLE": settings.APPLICATION_TITLE, "FIRST_NAME": user.first_name, "LAST_NAME": user.last_name, "PASSWORD_RESET_LINK": password_reset_link} text_content = plaintext.render(context) html_content = htmly.render(context) msg = EmailMultiAlternatives( subject, text_content, from_email, [ to_email, ]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_access_token_notifcation(token): plaintext = get_template('email-access-token-granted.txt') htmly = get_template('email-access-token-granted.html') context = {"APPLICATION_TITLE": settings.APPLICATION_TITLE, "APP_NAME": token.application.name, "HOSTNAME": get_hostname() } subject = '[%s] You just granted access to %s' % (settings.APPLICATION_TITLE, token.application.name) from_email = settings.DEFAULT_FROM_EMAIL to_email = token.user.email text_content = plaintext.render(context) html_content = htmly.render(context) msg = EmailMultiAlternatives( subject, text_content, from_email, [ to_email, ]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_mail(subject, email_template_name, recipients, html_email_template_name, context, email_from=DEFAULT_FROM_EMAIL): """ Sends an email to someone """ if 'test' in sys.argv: return # Don't send mails if we are testing to prevent spam if context['html']: body = loader.render_to_string(email_template_name, context) else: body = email_template_name email_message = EmailMultiAlternatives(subject, body, email_from, recipients) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send(fail_silently=True)
def send_mail(subject, txt_template, to, context=None, html_template=None, fail_silently=True): """ Multipart message helper with template rendering. """ site = Site.objects.get_current() context = context or {} context.update({ 'login_url': "http://%s" % urljoin(site.domain, admin_reverse('index')), 'title': subject, }) txt_body = render_to_string(txt_template, context) message = EmailMultiAlternatives(subject=subject, body=txt_body, to=to) if html_template: body = render_to_string(html_template, context) message.attach_alternative(body, 'text/html') message.send(fail_silently=fail_silently)
def mail_newsletter(recipients, mail): email_context = { 'title': mail.subject, 'message': mail.text, 'base_url': settings.EMAIL_ABS_URL, 'sponsors': Sponsor.objects.all(), } email_html = render_to_string('newsletter/email_newsletter.html', email_context) email_plaintext = render_to_string('newsletter/email_newsletter.txt', email_context) to = [x.email for x in recipients] # Create a map of emails to unsub tokens for the email merge unsub_tokens = {recipient.email: { 'unsub_url': '{hostname}{path}'.format(hostname=settings.EMAIL_ABS_URL, path=reverse('unsub_with_id', kwargs={ 'token': recipient.unsubscribe_token }))} for recipient in recipients} sender = '{name} <{email}>'.format(name=mail.sender_name, email=mail.sender_email) email = EmailMultiAlternatives(mail.subject, email_plaintext, sender, to) email.attach_alternative(email_html, 'text/html') email.merge_data = unsub_tokens email.send() # Create a function called "chunks" with two arguments, l and n:
def send_confirmation_mail(self, request, rental): subject = ('[Verleihtool] Your rental request, %s %s' % (rental.firstname, rental.lastname)) message = render_to_string('rental/mails/confirmation.md', { 'rental': rental }, request) email = EmailMultiAlternatives( subject=subject, body=message, to=[rental.email], cc=settings.CC_EMAIL, ) email.attach_alternative(markdown.markdown(message), 'text/html') email.send()