Example #1
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}"
            )
Example #2
0
    def sending_with_img(self):
        try:
            email_conn = smtplib.SMTP(self.host, self.port)
            email_conn.ehlo()
            email_conn.starttls()
            email_conn.login(self.admin_email, self.password)
            
            msg = MIMEMultipart('alternative')
            msg['Subject'] = self.subject
            msg['From'] = self.from_email
            msg['To'] = self.to_member_email

            sender = self.member_name
            sender_email = self.to_member_email
            subject = self.subject
            text = self.message

            img_name = ''
            img_path = ''
            
            for f in [
                'email_icon.png', 
                'inboxiconanimation_30.gif',
                'logo-lotus-bo-circle.png',
                'facebook_icon.png',
                'twitter_icon.png',
                'youtube_icon.png'
                ]:
                img_name = f
                img_path = 'img/' + f
                fp = open(os.path.join(os.path.dirname(__file__), img_path), 'rb')
                msg_img = MIMEImage(fp.read())
                fp.close()
                msg_img.add_header('Content-ID', '<{}>'.format(f))
                msg.mixed_subtype = 'related'
                msg.attach(msg_img)
            
            part1 = MIMEText(text, 'html')
            
            msg.attach(part1)
           
            email_conn.sendmail(self.from_email, self.to_member_email, msg.as_string())
            email_conn.quit()
        except smtplib.SMTPException:
            print("error sending email")
Example #3
0
    def send(self, testing=True, myself=True, request=None):
        """send mailing or test mailing"""

        import smtplib

        from django.core.urlresolvers import reverse
        from email.header import make_header
        from email.mime.text import MIMEText
        from email.mime.multipart import MIMEMultipart

        from ain7.annuaire.models import Person
        from ain7.filters_local import FILTERS


        url = reverse('mailing-view', args=[self.id])
        text = u"Si vous n'arrivez pas à voir ce mail correctement, merci de\
 vous\nrendre à l'URL "+url+u"\n\nL'équipe de l'AIn7"

        html = self.build_html_body()

        part1 = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
        part1.set_charset('utf-8')
        part2 = MIMEText(html.encode('utf-8'), 'html', 'utf-8')
        part2.set_charset('utf-8')

        msg = MIMEMultipart('alternative')
        title = self.title
        if testing:
            title = '[TEST] '+title
        msg['Subject'] = str(make_header([(title, 'utf-8')]))
        msg['Sender'] = u'*****@*****.**'
        msg['Presence'] = u'Bulk'
        msg['X-AIn7-Portal-Message-Rationale'] = u'Subscriber'
        msg.attach(part1)

        msg.attach(part2)

        msg.mixed_subtype = 'related'

        for img in ['logo_ain7.png', 'facebook.png', 'linkedin.png', 'twitter.png', 'googleplus.png']:
            fp = open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/emails/img', img), 'rb')
            msg_img = MIMEImage(fp.read())
            fp.close()
            msg_img.add_header('Content-ID', '<{}>'.format(img))
            msg.attach(msg_img)

        recipients = Person.objects.none()

        if request:
            recipients = Person.objects.filter(user__id=request.user.id)

        if testing and not myself:
            recipients = Person.objects.filter(
                groups__group__slug='ain7-mailing-tester'
            )

        if not testing:
            recipients = Person.objects.filter(FILTERS[self.mail_to.filter][1])

        smtp = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
        smtp.ehlo()

        for recipient in recipients:

            mail = recipient.mail_favorite()
            first_name = recipient.first_name
            last_name = recipient.last_name

            mail_modified = mail.replace('@', '=')

            del(msg['From'])
            msg['From'] = u'Association AIn7 <noreply+' + \
                mail_modified+'@ain7.com>'
            del(msg['To'])
            msg['To'] = first_name+' '+last_name+' <'+mail+'>'

            try:
                smtp.sendmail(
                    'noreply+'+mail_modified+'@ain7.com',
                    mail,
                    msg.as_string(),
                )

                mailingrecipient = MailingRecipient()
                mailingrecipient.person = recipient
                mailingrecipient.mailing = self
                mailingrecipient.testing = testing
                mailingrecipient.key = User.objects.make_random_password(50)
                mailingrecipient.save()

            except Exception:
                pass

        smtp.quit()

        if not testing:
            self.sent_at = datetime.datetime.now()
            self.save()
Example #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()