当前位置: 首页>>代码示例>>Python>>正文


Python message.EmailMultiAlternatives方法代码示例

本文整理汇总了Python中django.core.mail.message.EmailMultiAlternatives方法的典型用法代码示例。如果您正苦于以下问题:Python message.EmailMultiAlternatives方法的具体用法?Python message.EmailMultiAlternatives怎么用?Python message.EmailMultiAlternatives使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.mail.message的用法示例。


在下文中一共展示了message.EmailMultiAlternatives方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _email_student_note

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def _email_student_note(note):
    """
    Email advising note to student.
    """
    subject = "SFU Advising Note"
    from_email = note.advisor.email()
    if note.student is not None:
        email = note.student.email()
    else:
        email = note.nonstudent.email()
    content_html = note.html_content()
    content_text = note.text  # the creole/markdown is good enough for the plain-text version?
    attach = []
    if note.file_attachment:
        note.file_attachment.open()
        attach = [(note.attachment_filename(), note.file_attachment.read(), note.file_mediatype)]

    mail = EmailMultiAlternatives(subject=subject, body=content_text, from_email=from_email, to=[email],
                                  cc=[from_email], attachments=attach)
    mail.attach_alternative(content_html, 'text/html')
    mail.send() 
开发者ID:sfu-fas,项目名称:coursys,代码行数:23,代码来源:views.py

示例2: create_verification_notification

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def create_verification_notification(
        notification_type, user, user_address, data,
        template_config_data):
    from_email = registration_settings.VERIFICATION_FROM_EMAIL
    reply_to_email = (registration_settings.VERIFICATION_REPLY_TO_EMAIL or
                      from_email)
    template_context_builder = registration_settings.VERIFICATION_TEMPLATE_CONTEXT_BUILDER  # noqa: E501
    context = template_context_builder(
        user, user_address, data,
        notification_type=notification_type,
        notification_method=NotificationMethod.EMAIL)
    template_config = parse_template_config(template_config_data)

    subject = render_to_string(
        template_config.subject_template_name, context=context).strip()
    text_body = template_config.text_body_processor(
        render_to_string(
            template_config.text_body_template_name, context=context))

    email_msg = EmailMultiAlternatives(
        subject, text_body, from_email, [user_address],
        reply_to=[reply_to_email])

    if template_config.html_body_template_name:
        html_body = render_to_string(
            template_config.html_body_template_name, context=context)
        email_msg.attach_alternative(html_body, 'text/html')

    return email_msg 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:31,代码来源:email.py

示例3: bulk_email_view

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def bulk_email_view(self, request, object_id):
        season = get_object_or_404(Season, pk=object_id)
        if not request.user.has_perm('tournament.bulk_email', season.league):
            raise PermissionDenied

        if request.method == 'POST':
            form = forms.BulkEmailForm(season.seasonplayer_set.count(), request.POST)
            if form.is_valid() and form.cleaned_data['confirm_send']:
                season_players = season.seasonplayer_set.all()
                email_addresses = {sp.player.email for sp in season_players if
                                   sp.player.email != ''}
                email_messages = []
                for addr in email_addresses:
                    message = EmailMultiAlternatives(
                        form.cleaned_data['subject'],
                        form.cleaned_data['text_content'],
                        settings.DEFAULT_FROM_EMAIL,
                        [addr]
                    )
                    message.attach_alternative(form.cleaned_data['html_content'], 'text/html')
                    email_messages.append(message)
                conn = mail.get_connection()
                conn.open()
                conn.send_messages(email_messages)
                conn.close()
                self.message_user(request, 'Emails sent to %d players.' % len(season_players),
                                  messages.INFO)
                return redirect('admin:tournament_season_changelist')
        else:
            form = forms.BulkEmailForm(season.seasonplayer_set.count())

        context = {
            'has_permission': True,
            'opts': self.model._meta,
            'site_url': '/',
            'original': season,
            'title': 'Bulk email',
            'form': form
        }

        return render(request, 'tournament/admin/bulk_email.html', context) 
开发者ID:cyanfish,项目名称:heltour,代码行数:43,代码来源:admin.py

示例4: __init__

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def __init__(self, message, fail_silently=True):
        try:
            message_dict = {}
            message_dict["From"] = message.from_email
            message_dict["Subject"] = unicode(message.subject)
            message_dict["TextBody"] = unicode(message.body)

            if message.to:
                message_dict["To"] = ",".join(message.to)

            if message.cc:
                message_dict["Cc"] = ",".join(message.cc)

            if message.bcc:
                message_dict["Bcc"] = ",".join(message.bcc)

            if isinstance(message, EmailMultiAlternatives):
                    for alt in message.alternatives:
                        if alt[1] == "text/html":
                            message_dict["HtmlBody"] = unicode(alt[0])

            if len(message.extra_headers):
                message_dict["Headers"] = [{"Name": x[0], "Value": x[1]} for x in message.extra_headers.items()]
            if message.attachments and isinstance(message.attachments, list):
                if len(message.attachments):
                    message_dict["Attachments"] = message.attachments

        except:
            if fail_silently:
                message_dict = {}
            else:
                raise
        super(PostmarkMessage, self).__init__(message_dict) 
开发者ID:arguman,项目名称:arguman.org,代码行数:35,代码来源:postmark_backend.py

示例5: _mail_admins_with_attachment

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def _mail_admins_with_attachment(
            subject,
            message,
            fail_silently=True,
            connection=None,
            html_message=None,
            attachments=None,
            extra_recipients: Optional[List[str]] = None,
    ):
        """
        Mimics mail_admins, but allows attaching files to the message
        """
        if not settings.ADMINS and not extra_recipients:
            return

        recipients = [a[1] for a in settings.ADMINS] + extra_recipients
        mail = EmailMultiAlternatives(
            "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
            message, settings.SERVER_EMAIL, recipients,
            connection=connection
        )

        if html_message:
            mail.attach_alternative(html_message, "text/html")

        if attachments:
            for attachment_name, attachment_content, attachment_mime in attachments:
                mail.attach(attachment_name, attachment_content, attachment_mime)

        mail.send(fail_silently=fail_silently)


# Functions ##################################################################### 
开发者ID:open-craft,项目名称:opencraft,代码行数:35,代码来源:utilities.py

示例6: send_mail

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def send_mail(subject, message, recipient_list, from_email=None, **kwargs):
    """
    Wrapper around Django's EmailMultiAlternatives as done in send_mail().
    Custom from_email handling and special Auto-Submitted header.
    """
    if not from_email:
        if hasattr(settings, 'WAGTAILADMIN_NOTIFICATION_FROM_EMAIL'):
            from_email = settings.WAGTAILADMIN_NOTIFICATION_FROM_EMAIL
        elif hasattr(settings, 'DEFAULT_FROM_EMAIL'):
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            from_email = 'webmaster@localhost'

    connection = kwargs.get('connection', False) or get_connection(
        username=kwargs.get('auth_user', None),
        password=kwargs.get('auth_password', None),
        fail_silently=kwargs.get('fail_silently', None),
    )
    multi_alt_kwargs = {
        'connection': connection,
        'headers': {
            'Auto-Submitted': 'auto-generated',
        }
    }
    mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, **multi_alt_kwargs)
    html_message = kwargs.get('html_message', None)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    return mail.send() 
开发者ID:wagtail,项目名称:wagtail,代码行数:32,代码来源:mail.py

示例7: send_multi_format_email

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def send_multi_format_email(template_prefix, template_ctxt, target_email):
        subject_file = 'authemail/%s_subject.txt' % template_prefix
        txt_file = 'authemail/%s.txt' % template_prefix
        html_file = 'authemail/%s.html' % template_prefix

        subject = render_to_string(subject_file).strip()
        from_email = settings.DEFAULT_EMAIL_FROM
        to = target_email
        bcc_email = settings.DEFAULT_EMAIL_BCC
        text_content = render_to_string(txt_file, template_ctxt)
        html_content = render_to_string(html_file, template_ctxt)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
                  bcc=[bcc_email])
        msg.attach_alternative(html_content, 'text/html')
        msg.send() 
开发者ID:celiao,项目名称:django-rest-authemail,代码行数:17,代码来源:models.py

示例8: send_messages

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def send_messages(self, email_messages):
    if not email_messages:
      return

    for message in email_messages:

      content = {}
      if isinstance(message, EmailMessage):
        content["text/%s" % message.content_subtype] = message.body

      if isinstance(message, EmailMultiAlternatives):
        for alt in message.alternatives:
          content[alt[1]] = alt[0]

      output = '''
----------------------------------------
Redirecting email to log.

From: %s
To: %s
Bcc: %s
Subject: %s
''' % (
        repr(message.from_email),
        repr(message.to),
        repr(message.bcc),
        repr(message.subject),
      )
      for n, v in message.extra_headers.items():
        output += '%s: %s\n' % (n, repr(v))
      for contentType, content in content.items():
        output += '\n'
        output += '-- Email body as %s --\n' % contentType
        output += content
        output += '\n'
        output += '-- End of email body as %s --\n' % contentType
      output += '-' * 40
      output += '\n'
      logger.info(output) 
开发者ID:Polychart,项目名称:builder,代码行数:41,代码来源:emailConsole.py

示例9: send_email

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def send_email(self, filename):
        # send email
        email = EmailMultiAlternatives(
            subject='[Olympia tradingdb backup]',
            body='tradingdb backup attached.',
            from_email=settings.SERVER_EMAIL,
            to=[a[1] for a in settings.ADMINS]
        )
        email.attach_file(filename)
        email.send() 
开发者ID:gnosis,项目名称:pm-trading-db,代码行数:12,代码来源:db_dump.py

示例10: make_email_backend_message

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def make_email_backend_message(self, email_message):
        """
        Given an instance of EmailMessage, returns a Django/Email backend email message. This allows us to test the
        unsubscription logic.
        """
        headers = {'List-Unsubscribe': email_message.unsubscribe_links.get("action_unsubscribe_link")}
        mail = EmailMultiAlternatives(email_message.subject, email_message.body_text,
                                      email_message.from_email, [email_message.to_email],
                                      headers=headers)
        mail.attach_alternative(email_message.body_html, "text/html")
        return mail 
开发者ID:canvasnetworks,项目名称:canvas,代码行数:13,代码来源:email_channel.py

示例11: _send_sample_manifest

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def _send_sample_manifest(sample_manifest_rows, kit_id, original_filename, original_file_rows, user, project):

    # write out the sample manifest file
    wb = xl.Workbook()
    ws = wb.active
    ws.title = "Sample Info"

    ws.append(MergedPedigreeSampleManifestConstants.SAMPLE_MANIFEST_HEADER_ROW1)
    ws.append(MergedPedigreeSampleManifestConstants.SAMPLE_MANIFEST_HEADER_ROW2)

    for row in sample_manifest_rows:
        ws.append([row[column_key] for column_key in MergedPedigreeSampleManifestConstants.SAMPLE_MANIFEST_COLUMN_NAMES])

    temp_sample_manifest_file = tempfile.NamedTemporaryFile()
    wb.save(temp_sample_manifest_file.name)
    temp_sample_manifest_file.seek(0)

    sample_manifest_filename = kit_id+".xlsx"
    logger.info("Sending sample manifest file %s to %s" % (sample_manifest_filename, UPLOADED_PEDIGREE_FILE_RECIPIENTS))

    original_table_attachment_filename = '{}.xlsx'.format('.'.join(os.path.basename(original_filename).split('.')[:-1]))

    email_body = "User {} just uploaded pedigree info to {}.<br />".format(user.email or user.username, project.name)

    email_body += """This email has 2 attached files:<br />
    <br />
    <b>%(sample_manifest_filename)s</b> is the sample manifest file in a format that can be sent to GP.<br />
    <br />
    <b>%(original_filename)s</b> is the original merged pedigree-sample-manifest file that the user uploaded.<br />
    """ % locals()

    temp_original_file = tempfile.NamedTemporaryFile()
    wb_out = xl.Workbook()
    ws_out = wb_out.active
    for row in original_file_rows:
        ws_out.append(row)
    wb_out.save(temp_original_file.name)
    temp_original_file.seek(0)

    email_message = EmailMultiAlternatives(
        subject=kit_id + " Merged Sample Pedigree File",
        body=strip_tags(email_body),
        to=UPLOADED_PEDIGREE_FILE_RECIPIENTS,
        attachments=[
            (sample_manifest_filename, temp_sample_manifest_file.read(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
            (original_table_attachment_filename, temp_original_file.read(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
        ],
    )
    email_message.attach_alternative(email_body, 'text/html')
    email_message.send() 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:52,代码来源:pedigree_info_utils.py

示例12: dispatch

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def dispatch(self, object, *args, **kwargs):
        self.object = object
        self.kwargs = kwargs
        receivers = self.get_receivers()
        context = self.get_context()
        context.update(kwargs)
        attachments = self.get_attachments()
        template = self.template_name

        mails = []
        mail_exceptions = []
        for receiver in receivers:
            context['receiver'] = receiver
            (subject, text, html) = self.render(template, context)
            context.pop('receiver')

            if hasattr(receiver, 'email'):
                to_address = receiver.email
            else:
                to_address = receiver

            subject_clean = re.sub(r'[\r\n]', '', subject).strip()

            mail = EmailMultiAlternatives(
                subject=subject_clean,
                body=text,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[to_address],
                reply_to=self.get_reply_to(),
            )

            if len(attachments) > 0:
                mail.mixed_subtype = 'related'

                for attachment in attachments:
                    mail.attach(attachment)

            mail.attach_alternative(html, 'text/html')
            mails.append(mail)

            if self.enable_reporting:
                try:
                    mail.send()
                except SMTPException as exc:
                    mail_exceptions.append(exc)
            else:
                mail.send()

        if self.enable_reporting:
            self.handle_report(mails, mail_exceptions)

        return mails 
开发者ID:liqd,项目名称:adhocracy4,代码行数:54,代码来源:base.py

示例13: send_messages

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def send_messages(self, email_messages):

    if not email_messages:
      return
    errors = []

    for message in email_messages:

      content = {}
      if isinstance(message, EmailMessage):
        content["text/%s" % message.content_subtype] = message.body

      if isinstance(message, EmailMultiAlternatives):
        for alt in message.alternatives:
          content[alt[1]] = alt[0]

      message_dict = {
        'api_key': getattr(settings, "EMAIL_POSTAGEAPP_API_KEY"),
        'arguments': {
          'recipients': message.to,
          'headers': {
            "subject": message.subject,
            "from": message.from_email,
            "bcc": message.bcc,
          },
          'content': content,
        }
      }

      if getattr(message, "extra_headers"):
        message_dict["arguments"]["headers"].update(message.extra_headers)

      try:
        req = urllib2.Request(self.postageapp_endpoint, json.dumps(message_dict), {'Content-Type': 'application/json'})
        response = urllib2.urlopen(req)

      except urllib2.HTTPError, e:
        jsonobj = None
        try: jsonobj = json.loads(e.read())
        except Exception, e: pass

        if jsonobj is not None: errors.append(jsonobj)
        else: errors.append('Unknown Error') 
开发者ID:Polychart,项目名称:builder,代码行数:45,代码来源:postageapp.py

示例14: send_emails

# 需要导入模块: from django.core.mail import message [as 别名]
# 或者: from django.core.mail.message import EmailMultiAlternatives [as 别名]
def send_emails(project_id, project_members, subject, message, all_members=False):
    """
    Sends emails from project coordinator to project members.
    """
    project = DataRequestProject.objects.get(id=project_id)

    template = engines["django"].from_string(message)
    logger.info("Sending {0} emails".format(len(project_members)))
    if all_members:
        project_members = project.project_members.filter_active().all()
    for project_member in project_members:
        if isinstance(project_member, str):
            # As the instance was passed as json, we need to lookup the db
            # object
            project_member = DataRequestProjectMember.objects.get(
                project_member_id=project_member
            )
        context = {
            "message": template.render(
                {"PROJECT_MEMBER_ID": project_member.project_member_id}
            ),
            "project": project.name,
            "username": project_member.member.user.username,
            "activity_management_url": full_url(
                reverse("activity", kwargs={"slug": project.slug})
            ),
            "project_message_form": full_url(
                reverse("activity-messaging", kwargs={"source": project.slug})
            ),
        }

        plain = render_to_string("email/project-message.txt", context)
        headers = {"Reply-To": project.contact_email}
        email_from = "{} <{}>".format(project.name, "support@openhumans.org")

        mail = EmailMultiAlternatives(
            subject,
            plain,
            email_from,
            [project_member.member.primary_email.email],
            headers=headers,
        )
        mail.send() 
开发者ID:OpenHumans,项目名称:open-humans,代码行数:45,代码来源:tasks.py


注:本文中的django.core.mail.message.EmailMultiAlternatives方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。