コード例 #1
0
ファイル: models.py プロジェクト: simbha/gocdn
    def sendActivationMail(self):
        from django.contrib.sites.models import Site
        from django.core.mail import EmailMessage
        from django.template.loader import render_to_string
        from django.core.urlresolvers import reverse
        from email.mime.image import MIMEImage
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText


        current_site = Site.objects.get(id=settings.SITE_ID)
        subject = u"Gostream.com aktivasyon kodunuz"
        url = reverse('user_activate', kwargs={'actcode':self.activation_code})
        print url
        img_content_id = 'mail_confirmation.jpg'
        #TODO
        img_data = open('/Users/yasemenkarakoc/netcen/gostream/static/images/mail_confirmation.jpg', 'rb').read()
        msg = MIMEMultipart(_subtype='related')

        body = 'cid:%s' % img_content_id

        html_content = render_to_string('email/mail_activation.html',
                {'email': self.email, 'url': url, 'current_site':current_site, 'body':body})

        msg = EmailMessage(subject, html_content, settings.DEFAULT_FROM_EMAIL, [self.email])
        msg.content_subtype = "html"
        msg = email_embed_image(msg, img_content_id, img_data)
        msg.send()
コード例 #2
0
    def send_email(
        self,
        smtp_client,
        recipient,
        subject,
        html=True,
        message=None,
        template=None,
        context=None,
        attachments=None,
    ):
        """
        Sends an email
        """

        email = MIMEMultipart()
        email["Subject"] = "{}\n".format(subject)
        email["To"] = recipient
        email["From"] = self.user

        if not context:
            context = {}

        if not message:
            message = render_to_string(template, context)

        if html:
            email.attach(MIMEText(message.encode("utf-8"), "html", _charset="utf-8"))
            email.attach(self.logo_img())
            email.content_subtype = "html"
            email.mixed_subtype = "related"
        else:
            email.attach(MIMEText(message.encode("utf-8"), "plain", _charset="utf-8"))

        if attachments:
            for attachement in attachments:
                mimetype, encoding = guess_type(attachement)
                mimetype = mimetype.split("/", 1)
                with open(attachement, "rb") as fh:
                    attachment = MIMEBase(mimetype[0], mimetype[1])
                    attachment.set_payload(fh.read())

                encode_base64(attachment)
                attachment.add_header(
                    "Content-Disposition",
                    "attachment",
                    filename=attachement.split("/")[-1],
                )
                email.attach(attachment)
                log.debug(f"{self} added email attachment {attachment}")

        try:
            smtp_client.sendmail(self.user, recipient, email.as_string())
            log.info(f"Sent email with subject {subject} to {recipient}")
        except Exception as e:
            raise notification_utils.EmailException(
                f"{self} failed to send email with {e}"
            )
コード例 #3
0
ファイル: views.py プロジェクト: CTSC/HFC
 def form_valid(self, form):
     users = form.cleaned_data['users']
     subject = form.cleaned_data['subject']
     message = form.cleaned_data['message']
     from_email = 'HackForChange Team<*****@*****.**>'
     headers = {'Reply-To': '*****@*****.**'}
     for user in users:
         msg = MIMEMultipart('alternative')
         html_content = render_to_string('HFC/invitation_email.html', {
             'message': message,
             'name': user.name
         })
         msg = EmailMessage(subject,
                            html_content,
                            from_email, [
                                user.email,
                            ],
                            headers=headers)
         msg.content_subtype = "html"
         msg.send(fail_silently=True)
     return super(SendUserEmails, self).form_valid(form)
コード例 #4
0
 def run(self):
     msg = EmailMultiAlternatives(self.subject,
                                  self.body,
                                  self.from_email,
                                  bcc=self.recipient_list)
     if self.html:
         msg.attach_alternative(self.html, "text/html")
         msg.content_subtype = 'html'
         msg.mixed_subtype = 'related'
         if self.images:
             for image in self.images:
                 # Create an inline attachment
                 ext = '.' + image.image.url.split('.')[-1]
                 image = MIMEImage(image.image.read(), _subtype=ext)
                 image.add_header('Content-ID',
                                  '<{}>'.format(image.image_filename))
                 msg.attach(image)
     i = 0
     recipients_list_ = self.recipient_list[i:i + NBR_RECIPIENTS_BY_TIME]
     while len(recipients_list_) > 0:
         recipients_list_ = self.recipient_list[i:i +
                                                NBR_RECIPIENTS_BY_TIME]
         msg.bcc = recipients_list_
         try:
             msg.send(self.fail_silently)
         except smtplib.SMTPDataError:
             print("SMTPDataError.......................")
             print("recipients_list_:")
             print(str(recipients_list_))
             is_ok = False
             msg2 = MIMEMultipart('alternative')
             msg2['Subject'] = self.subject
             msg2['From'] = self.from_email
             msg2['bcc'] = ", ".join(recipients_list_)
             part1 = MIMEText(self.body, 'plain')
             part2 = MIMEText(self.html, 'html')
             msg2.attach(part1)
             msg2.attach(part2)
             msg2.content_subtype = 'html'
             msg2.mixed_subtype = 'related'
             if self.images:
                 for image in self.images:
                     ext = '.' + image.image.url.split('.')[-1]
                     image = MIMEImage(image.image.read(), _subtype=ext)
                     image.add_header('Content-ID',
                                      '<{}>'.format(image.image_filename))
                     msg2.attach(image)
             for added_email_account in settings.ADDED_EMAILS_ACCOUNTS:
                 print("is_ok: " + str(is_ok))
                 if is_ok:
                     break
                 try:
                     send_python_email(added_email_account['host_user'],
                                       added_email_account['host_password'],
                                       msg2, recipients_list_)
                     is_ok = True
                 except Exception as e:
                     # for the repr
                     print("the repr: ")
                     print(repr(e))
                     # for just the message, or str(e), since print calls str under the hood
                     print("just the message, or str(e): ")
                     print(e)
                     # the arguments that the exception has been called with.
                     # the first one is usually the message. (OSError is different, though)
                     print(
                         "the arguments that the exception has been called with: "
                     )
                     print(e.args)
         i += NBR_RECIPIENTS_BY_TIME
     if self.args_tuple and self.args_tuple[0] is False:
         SendNewsletterAfterActivating.objects.filter(
             item_id=self.args_tuple[1]).delete()
コード例 #5
0
ファイル: base_helper.py プロジェクト: rexlertech/rexler
def send_email(subject, email_to, body, context):
    email = MIMEMultipart(_subtype='related')
    html_content = render_to_string(body, context)
    email = EmailMessage(subject, html_content, to=[email_to])
    email.content_subtype = "html"  # Main content is now text/html
    email.send()