def sendMail(request): if request.method == 'GET': mail = Mail.objects.all() serializer = MailSerializer(mail, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = MailSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() remitente = request.DATA['remitente'] destinatario = request.DATA['destinatario'] asunto = request.DATA['asunto'] mensaje = request.DATA['mensaje'] msg = EmailMultiAlternatives( subject="%s" % asunto, body="This is the text email body", from_email="<%s>" % remitente, to=["Recipient One <%s>" % destinatario], headers={'Reply-To': "Service <*****@*****.**>" } # optional extra headers ) msg.attach_alternative("<p>%s</p>" % mensaje, "text/html") msg.tags = ["one tag", "two tag", "red tag", "blue tag"] msg.metadata = {'user_id': "8675309"} msg.send() return Response("Mail sent to: %s" % destinatario) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
def send_trigger_email( subject_email, from_email, to_email, content_email, content_type, ): msg = EmailMultiAlternatives( subject=subject_email, from_email=from_email, to=to_email, ) msg.attach_alternative( content_email, content_type, ) msg.tags = [] msg.metadata = {} msg.send() response_f = {} response_m = msg.mandrill_response[0] response_f = response_m if response_f['status'] == 'sent': print """as expected, the message was sent. """ else: # msg.error(msg) print """
def send_associated_to_tenant_email(self, tenant): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ context = { 'user': self, 'quoted_email': http.urlquote(self.email), 'activation_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': {'name': settings.SITE_NAME, 'url': settings.SITE_URL}, 'tenant': tenant.name } plaintext_context = Context(autoescape=False) # HTML escaping not appropriate in plaintext subject = render_to_string("account/emails/associated_to_tenant_subject.txt", context, plaintext_context) subject = ''.join(subject.splitlines()) text_body = render_to_string("account/emails/associated_to_tenant_message.txt", context, plaintext_context) html_body = render_to_string("account/emails/associated_to_tenant_message.html", context) message = EmailMultiAlternatives(subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[self.email], body=text_body) message.attach_alternative(html_body, "text/html") message.tags = ["associated_to_tenant"] message.send()
def send_email(self): message = self.trigger.message context_dict = {'volunteer': self.volunteer, 'assignment': self.assignment} body = message.rendered_body(context_dict) email_params = { 'subject': message.rendered_subject(context_dict), 'to': [self.volunteer.email_address], 'from_email': settings.FROM_ADDRESS, } if message.body_is_html: email = EmailMultiAlternatives(**email_params) email.attach_alternative(body, "text/html") email.auto_text = True else: email = EmailMessage(**email_params) email.body = body email.auto_html = True name_tag = ("name - %s" % message.name)[:50] trigger_tag = ("trigger - %s" % self.trigger.id)[:50] email.tags = [name_tag, trigger_tag] logger.info("Sending %s" % email_params) print("Sending %s" % email_params) try: email.send(fail_silently=False) self.sent_date = date.today() except MandrillAPIError: print("FAILED %s" % email_params) self.send_failed = True self.save() return not self.send_failed
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None): """ Generates a one-use only link for resetting password and sends to the user. """ from django.core.mail import EmailMultiAlternatives from django.utils.http import int_to_base36 for user in self.users_cache: c = { 'email': user.email, 'site': {'name': settings.SITE_NAME, 'url': settings.SITE_URL}, 'uid': int_to_base36(user.pk), 'user': user, 'token': token_generator.make_token(user), } subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = loader.render_to_string(email_template_name, c) message = EmailMultiAlternatives(subject=subject, from_email=from_email, to=[user.email], body=email) if html_email_template_name: html_email = loader.render_to_string(html_email_template_name, c) message.attach_alternative(html_email, "text/html") message.tags = ["password_reset"] message.send()
def event_mail(email, first_name, last_name, username, rider_class, event, confirmation_number): msg = EmailMultiAlternatives( subject="You're Registered!", from_email="The Lobos Team <*****@*****.**>", to=[email], reply_to=["Lobos Support <*****@*****.**>"]) html = loader.render_to_string( '../templates/events/eventregistertemplate.html', { 'event': event, 'rider_class': rider_class, 'name': first_name.title() + " " + last_name.title(), 'username': username, 'first_name': first_name.title(), 'last_name': last_name.title, 'confirmation_number': confirmation_number, }) msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.tags = ["event_registration"] msg.track_clicks = True # Send it: msg.send()
def send_mail_worker(self, host, campaign, sector, campaign_log): # Build cache key to show progress cache_key = 'progress-campaign:{}'.format(campaign_log.id) body = campaign.html_mail.read() connection = get_connection() messages = [] for email in sector.email_set.all(): # Build message msg = EmailMultiAlternatives( subject=campaign.title, body='', from_email=u"{from_name} <{from_email}>".format(from_name=campaign.from_name, from_email=campaign.from_email), ) # Optional Mandrill-specific extensions: msg.tags = campaign.get_tags() msg.async = True msg.track_opens = True msg.track_clicks = True msg.to = [email.address] msg.attach_alternative(attach_remove_link(host, body, email), "text/html") messages.append(msg) # Send mass emails connection.send_messages(messages, cache_key) # Change status campaign_log.is_sent = True campaign_log.save() cache.delete(cache_key)
def send_confirmation_email(request, user): current_site = get_current_site(request) uid = urlsafe_base64_encode(force_bytes(user.pk)) token = account_activation_token.make_token(user) html_message = loader.render_to_string( 'account_activation_email.html', { 'user': user, 'domain': request.META['HTTP_HOST'], 'uid': uid, 'token': token, 'referral_link': user.profile.referral.url }) message = 'http://' + request.META['HTTP_HOST'] + '/activate/' + str( uid) + '/' + str(token) subject = 'Thank you for signing up! ' from_email = 'Check My Keywords <*****@*****.**>' msg = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=[user.first_name + ' ' + user.last_name + '<' + user.email + '>'], reply_to=["Support <*****@*****.**>"]) # Include an inline image in the html: html = html_message msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.metadata = {"user_id": request.user.id} msg.tags = ["confirmation_email"] msg.track_clicks = True # Send it: msg.send()
def send_newsletter_signup(request, extra_context): """ Necessary context: 'subject', 'recipient_email', 'category' category object Optional: 'button_link' 'button_text' """ # text_content = 'Welcome to the newsletter.\nPlease activate your subscription by this link: {}\n\nKind regards,\n/Comunidad Ibiza\n\nUnsubscribe here: %tag_unsubscribe_url%'.format(url) # html_content = '<p>Welcome to the newsletter.<br>Please activate your subscription <a href="{}">here</a></p><p>Kind regards,<br>/Comunidad Ibiza</p><p><a href="%tag_unsubscribe_url%">Unsubscribe</a></p>'.format(url) context = { 'logo': request.build_absolute_uri("static/newsletter/logo-192x192.png") } context.update(extra_context) category = context['category'] c = Context(context) text_content = render_to_string('email_templates/confirm.txt', c) html_content = render_to_string('email_templates/beefree-confirm.html', c) # import ipdb; ipdb.set_trace() msg = EmailMultiAlternatives( extra_context['subject'], text_content, settings.DEFAULT_FROM_EMAIL, [extra_context['recipient_email']], ) msg.attach_alternative(html_content, "text/html") msg.tags = [category.tag] msg.send() logger.info("Confirmation email sent to {}".format( extra_context['recipient_email']))
def send_reset_email(request, user): current_site = get_current_site(request).domain reset_url = 'https://' + 'checkmykeywords.com' + '/user/change/password/' + str( user.profile.password_reset_token) message = reset_url subject = 'Reset your password' from_email = 'Check My Keywords <*****@*****.**>' html_message = loader.render_to_string('account_reset_email.html', { 'user': user, 'reset_url': reset_url }) msg = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=[user.first_name + ' ' + user.last_name + '<' + user.email + '>'], reply_to=["Support <*****@*****.**>"]) # Include an inline image in the html: html = html_message msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.metadata = {"user_id": request.user.id} msg.tags = ["reset_email"] msg.track_clicks = True # Send it: msg.send()
def events_static(request): form = ContactForm(request.POST or None) if request.method == 'POST': if form.is_valid(): data = form.cleaned_data name = data['name'] email = data['email'] phone_number = data['phone_number'] handicap = data['handicap'] message = data['body'] plain_message = ( 'Hello, \n \n There was a new member inquiry on the site.: \n \n' ) # Include a html template: text_content = plain_message + name + '\n Phonenumber: ' + \ phone_number + '\n Email: ' + email + '\n Handicap: ' + \ handicap + '\n Message: ' + message + '\n - WVGC Mail Bot' msg = EmailMultiAlternatives( subject="WCGC Membership Inquiry", body=text_content, from_email="WVGC Admin <*****@*****.**>", to=[FRONT_END_CONTACTFORM_EMAIL], ) # Optional Anymail extensions: msg.track_clicks = True msg.tags = ["Member Inquiry"] # Send it:d msg.send() messages.success(request, 'Request successfully sent.') return redirect("thankyou_static") return render(request, './front-end/pages/events.html', { 'events_active': True, 'form': form })
def send_email(asin_list, user_first_name, user_last_name, user_email): first_name = user_first_name last_name = user_last_name email_format = first_name + ' ' + last_name + '<' + user_email + '>' html_message = loader.render_to_string( 'email_reporting.html', { 'asin_list': asin_list, 'first_name': first_name, 'last_name': last_name } ) message = 'Your keywords report' subject = "Your Keyword's Report" from_email = 'Check My Keywords <*****@*****.**>' msg = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=[email_format], reply_to=["Support <*****@*****.**>"]) # Include an inline image in the html: html = html_message msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.tags = ["schedule_email"] msg.track_clicks = True # Send it: msg.send()
def send_email(subject, email, template, context, tags=list(), metadata=list(), request=None, reply_to=settings.DEFAULT_FROM_EMAIL, send_at=None): """ Renders template blocks and sends an email. :param subject: :param email: :param template: :param context: :param tags: :param metadata: :param request: :param reply_to: :param send_at: :return: """ context.update({ 'STATIC_URL': settings.STATIC_URL, 'domain': settings.HOSTNAME }) if request: context = RequestContext(request, context) template = get_template(template) html_content = template.render(Context(context)) text_content = strip_tags(html_content) kwargs = dict( subject=subject, body=text_content.strip(), from_email=settings.DEFAULT_FROM_EMAIL, to=[email], reply_to=[reply_to], ) message = EmailMultiAlternatives(**kwargs) message.attach_alternative(html_content, 'text/html') # Email tags message.tags = tags # Email metadata message.metadata = metadata # datetime.now(utc) + timedelta(hours=1) if send_at: message.send_at = send_at message. async = settings.EMAIL_ASYNC message.track_clicks = True message.track_opens = True message.send(fail_silently=True)
def send_email(self): msg = EmailMultiAlternatives( subject='Добавлено новое граффити!', body= 'Надо проверить!\nНазвание: %s\nОписание: %s\n\nhttp://%s/%s/graffities/graffiti/?checked__exact=0' % (self.cleaned_data['name'], self.cleaned_data['comment'], DOMEN, ADMIN_URL), from_email='Graffiti Map <%s>' % DEFAULT_FROM_EMAIL, to=MANAGERS, ) msg.tags = ["new graffiti", ] msg.send()
def send_email_reset_password_link(email=None, token=None): """ Send email to admin or user. :param email: :return: """ # full_path = os.path.realpath(__file__) # file_path = '%s/a.txt' % os.path.dirname(full_path) try: msg = EmailMultiAlternatives( subject="[MyAudiens] Reset your password", body="No worry if you forgot password", from_email="MyAudiens <*****@*****.**>", to=[email], reply_to=["SupportTeam <*****@*****.**>"]) ahref = """<a href="http://""" + settings.SITE_DOMAIN + """/change?user_email=""" + email + \ """&token=""" + token + """">Click here</a>""" # logo_cid = attach_inline_image_file(msg, os.path.dirname(full_path)+'/static/img/logo.png') html = """ <div><table><tbody> <tr><h3>Hi, """ + email + """ </h3></tr><tr><h4> Did you forget password to work in MyAudiens ?</h4></tr> <tr> <table> <tbody> <tr> <td width=30> </td> <td width=32 style="padding-top:30px;padding-bottom:32px;width:32px" valign="middle"> <img width="50" height="25" style="display:block;vertical-align:top" alt="Logo" src="https://ci5.googleusercontent.com/proxy/JEJXSgwcrst6ovJ_vSVTr320W1yFnzyjnd6ai5Eh0zsnzbSYH2wn1Ox8VoTU3ZFOtskE3OZQ35U65aZ-vy7qX-h9KMryJoRPUVvWZ3_r1858wX2EdnRS2r5I89bbmGS0NZfKTA=s0-d-e1-ft#http://landing.adobe.com/dam/global/images/creative-cloud.logo.red.268x200.png"></td> <td style="color:#333333;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:20px;padding-top:30px;padding-bottom:32px" valign="middle">No worry. It is simple.""" + ahref + """ </td> </tr></tbody> </table> </tr> </tbody></table><div> """ msg.attach_alternative(html, "text/html") # Optional Anymail extensions: # msg.metadata = {"user_id": "8675309", "experiment_variation": 1} # msg.tags = ["activation", "onboarding"] msg.track_clicks = True msg.tags = ["Approving"] send_flag = msg.send() print("reset mail send successful : " + str(send_flag)) print(ahref) return True except Exception as e: print('Exception: {}'.format(e)) return False
def send_email(token=None, username=None, email=None): """ Send email to admin or user. :param email: :return: """ # full_path = os.path.realpath(__file__) # file_path = '%s/a.txt' % os.path.dirname(full_path) try: msg = EmailMultiAlternatives( subject="Waiting for approval", # body="A new user has signed up and their account is pending approval.\n\n\n" + # " Account email is " + email + "\n User Name is " + username, from_email="MYAUDIENS <*****@*****.**>", to=[username + " <" + email + ">"], reply_to=["SupportTeam <*****@*****.**>"]) ahref = """<a href="http://""" + settings.SITE_DOMAIN + """/active?token=""" + str( token) + """">activate</a>""" # logo_cid = attach_inline_image_file(msg, os.path.dirname(full_path)+'/static/img/logo.png') html = """ <div><table><tbody> <tr><h3>Hi, """ + username + """ </h3></tr><tr><h4> You have signed up and your account is pending approval.</h4></tr> <tr> <table> <tbody> <tr> <td width=30> </td> <td width=32 style="padding-top:30px;padding-bottom:32px;width:32px" valign="middle"> <img width="50" height="25" style="display:block;vertical-align:top" alt="Logo" src="https://ci5.googleusercontent.com/proxy/JEJXSgwcrst6ovJ_vSVTr320W1yFnzyjnd6ai5Eh0zsnzbSYH2wn1Ox8VoTU3ZFOtskE3OZQ35U65aZ-vy7qX-h9KMryJoRPUVvWZ3_r1858wX2EdnRS2r5I89bbmGS0NZfKTA=s0-d-e1-ft#http://landing.adobe.com/dam/global/images/creative-cloud.logo.red.268x200.png"></td> <td style="color:#333333;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:20px;padding-top:30px;padding-bottom:32px" valign="middle">Please """ + ahref + """ your account</td> </tr></tbody> </table> </tr> </tbody></table><div> """ msg.attach_alternative(html, "text/html") # Optional Anymail extensions: # msg.metadata = {"user_id": "8675309", "experiment_variation": 1} # msg.tags = ["activation", "onboarding"] msg.track_clicks = True msg.tags = ["Approving"] sent = msg.send() print("confirm mail send successful : " + str(sent)) print(ahref) return True except Exception as e: print('Exception: {}'.format(e)) return False
def send_email(self, context={}): (html_email, txt_email) = self.render_email(**context) msg = EmailMultiAlternatives( subject=self.email_subject, body=txt_email, to=self.get_recipients(**context), ) msg.attach_alternative(html_email, "text/html") msg.tags = self.get_tags(**context) msg.metadata = self.get_metadata(**context) msg.send()
def send_email(type=None, username=None, email=None): """ Send email to admin or user. :param email: :return: """ try: if type == "User": print('user email') msg = EmailMultiAlternatives( subject="Account Pending Notification", body= "Your account is pending approval, please wait for admin approval.", from_email="*****@*****.**", to=[username + "<" + email + ">"]) # Optional Anymail extensions: msg.tags = ["Pending"] else: print('admin email') msg = EmailMultiAlternatives( subject="Waiting for approval", body= "a new user has signed up and their account is pending approval.\n\n\n" " Account email is " + email + "\n" " User Name is " + username, from_email="*****@*****.**", to=["Admin<*****@*****.**>"]) msg.tags = ["Approving"] msg.send() except Exception as e: print('Exception: {}'.format(e))
def send_activation_email(user): token = r.get(user.email) if not token: token = str(uuid4()) r.set(user.email, token) r.expire(user.email, 86400) # Expire in 24h r.set(token, user.email) r.expire(token, 86400) txt = "Click the following link to activate your JrC-account:\n" + \ "https://auth.jrc.no/activate/" + token + "/" msg = EmailMultiAlternatives( subject="Please activate your JrC account", body=txt, from_email="Junior Consulting AS <*****@*****.**", to=[user.email], reply_to=["Junior Consulting AS - IT <*****@*****.**"]) msg.tags = ["activation"] msg.send()
def send_email( subject, body, to, from_email=None, reply_to=None, tags=None, track_clicks=False, fail_silently=False, attachments=None, ): if tags is None: tags = [] tags += HACKATHON_NAME.lower() if to and not isinstance(to, (list, tuple)): to = [to] if reply_to and not isinstance(reply_to, (list, tuple)): reply_to = [reply_to] body_plain = html2text.html2text(body) msg = EmailMultiAlternatives( subject=subject, body=body_plain, from_email=from_email or HACKATHON_NAME + "<" + HACKATHON_EMAIL_NOREPLY + ">", to=to, reply_to=reply_to or [HACKATHON_NAME + "<" + HACKATHON_EMAIL_CONTACT + ">"], attachments=attachments, ) msg.attach_alternative(body, "text/html") if tags: msg.tags = tags msg.track_clicks = track_clicks return msg.send(fail_silently=fail_silently)
def send_email(username=None, email=None): """ Send email to admin or user. :param email: :return: """ print('sending mail') try: msg = EmailMultiAlternatives( subject="Your account has already been approved", body="Your account has been approved by admin", from_email="*****@*****.**", to=[username + "<" + email + ">"]) msg.tags = ["Approved"] msg.track_clicks = True msg.send() except Exception as e: print('Exception: {}'.format(e))
def send(self, to, text_body, html_body=None, subject=None, tags=None, metadata=None): """Send the e-mail. :param to: Recipient of the e-mail. :param text_body: Plain text e-mail body. :param html_body: Rich HTML e-mail body. :param subject: Subject. If not provided, the class instance variable will be used. """ from_combined = '%s <%s>' % ( self.from_name, self.from_email ) if self.from_name else self.from_email message = EmailMultiAlternatives(subject or self.subject, text_body, from_combined, [to]) if html_body: message.attach_alternative(html_body, "text/html") # Attach any files. for filename, (data, mime_type) in self.attachments.items(): message.attach(filename, data, mime_type) # Optional Mandrill-specific extensions: if tags: message.tags = tags if metadata: message.metadata = metadata # Send the message. message.send()
def send_mail(self, sender, recipients, context=None, cc=None, bcc=None, sender_name="", attachments=None): """ This method sends the mail with the given parameters, replacing any variable fields with those in the context """ if cc is None: cc = [] if bcc is None: bcc = [] if attachments is None: attachments = {} plainBody = Template(self.email_object.plainBody).render( Context(context)) htmlBody = Template(self.email_object.htmlBody).render( Context(context)) email = EmailMultiAlternatives() email.subject = Template(self.email_object.subject).render( Context(context)) email.body = plainBody email.attach_alternative(htmlBody, 'text/html') email.from_email = "%s <%s>" % (sender_name, sender) email.to = recipients email.cc = cc email.bcc = bcc for attachment in self.email_object.attachments.all(): email.attach( "%s.%s" % (attachment.name, attachment.fileAttachment.file.name.split(".")[-1]), attachment.fileAttachment.file.read()) for attachment in attachments: email.attach(attachment['filename'].encode('ascii', 'ignore'), attachment['data']) email.tags = map(unicode.strip, self.email_object.tags.split(',')) email.track_clicks = True return email.send()
def general_email(subject, header, subheader, emailmessage, recipients): msg = EmailMultiAlternatives( subject=subject, from_email="The Lobos Team <*****@*****.**>", to=recipients, reply_to=["Lobos Support <*****@*****.**>"], ) msg.merge_data = {} msg.merge_global_data = {} html = loader.render_to_string('../templates/events/generalemail.html', { 'header': header, 'subheader': subheader, 'message': emailmessage, }) msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.tags = ["general communication"] msg.track_clicks = True # Send it: msg.send()
def send_email(subject, to_address, text_email='', html_email='', tags=None, metadata=None): # to=["New User <*****@*****.**>", "*****@*****.**"] from_email = "emondo <{0}>".format(settings.DEFAULT_FROM_EMAIL) msg = EmailMultiAlternatives(subject=subject, body=text_email, from_email=from_email, to=to_address, reply_to=[from_email]) msg.attach_alternative(html_email, "text/html") # Optional Anymail extensions: msg.metadata = metadata msg.tags = tags msg.track_clicks = True # Send it: msg.send()
def send_mail_user_reg(email, first_name, last_name, username, password): msg = EmailMultiAlternatives( subject="Welcome to Lobos", from_email="The Lobos Team <*****@*****.**>", to=[email], reply_to=["Lobos Support <*****@*****.**>"]) html = loader.render_to_string( '../templates/events/userregistertemplate.html', { 'name': first_name.title() + " " + last_name.title(), 'username': username, 'first_name': first_name.title(), 'last_name': last_name.title, 'password': password, }) msg.attach_alternative(html, "text/html") # Optional Anymail extensions: msg.tags = ["activation", "onboarding"] msg.track_clicks = True # Send it: msg.send()
def send_email_message(msg_path, recipient=None, dry_run=False): email_path = os.path.join(msg_path, "email.html") with open(email_path, "r") as body_f: body = body_f.read() intervention = get_intervention_from_path(email_path) if not intervention: return if intervention.sent: logger.info("Refusing to resend %s", intervention) return logger.info("Sending message to %s", intervention) if settings.DEBUG: # Belt-and-braces to ensure we don't accidentally send to # real users to = settings.TEST_EMAIL_TO else: to = intervention.contact.email if recipient: # Always allow overriding the test fax recipient to = recipient subject = ( "Information about your nimodipine prescribing from OpenPrescribing.net" ) msg = EmailMultiAlternatives( subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[to], reply_to=[settings.DEFAULT_FROM_EMAIL], ) msg = inline_images(msg, body) msg.tags = ["nimodipine"] msg.body = email_as_text(msg.alternatives[0][0]) msg.track_clicks = True if not dry_run: msg.send() intervention.sent = True intervention.save()
def send_associated_to_tenant_email(self, tenant): """ Sends a activation email to the user. This email is send when the user wants to activate their newly created user. """ context = { 'user': self, 'quoted_email': http.urlquote(self.email), 'activation_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': { 'name': settings.SITE_NAME, 'url': settings.SITE_URL }, 'tenant': tenant.name } plaintext_context = Context( autoescape=False) # HTML escaping not appropriate in plaintext subject = render_to_string( "account/emails/associated_to_tenant_subject.txt", context, plaintext_context) subject = ''.join(subject.splitlines()) text_body = render_to_string( "account/emails/associated_to_tenant_message.txt", context, plaintext_context) html_body = render_to_string( "account/emails/associated_to_tenant_message.html", context) message = EmailMultiAlternatives( subject=subject, from_email=settings.DEFAULT_FROM_EMAIL, to=[self.email], body=text_body) message.attach_alternative(html_body, "text/html") message.tags = ["associated_to_tenant"] message.send()
def send_email(self, verbose=False): # Return whether or not the sendable was sent. message = self.trigger.message body = self.email_body() email_params = { 'subject': message.rendered_subject(self._email_context_dict()), 'to': [self.volunteer.email_address], 'bcc': self.trigger.bcc(), 'from_email': self.trigger.campaign.from_address, } if message.body_is_html: email = EmailMultiAlternatives(**email_params) email.attach_alternative(body, "text/html") email.auto_text = True else: email = EmailMessage(**email_params) email.body = body email.auto_html = True # Tags are a mandril feature. name_tag = ("name - %s" % message.name)[:50] trigger_tag = ("trigger - %s" % self.trigger.id)[:50] email.tags = [name_tag, trigger_tag] logger.info("Sending %s" % email_params) if verbose: print("Sending %s" % email_params) try: email.send(fail_silently=False) self.sent_date = date.today() except MandrillAPIError: print("FAILED %s" % email_params) self.send_failed = True self.save() return not self.send_failed
def contact_static(request): form = ContactForm(request.POST or None) if request.method == 'POST': if form.is_valid(): print 'form valid' data = form.cleaned_data name = data['name'] email = data['email'] event_type = data['event_type'] event_date = data['event_date'] phone_number = data['phone_number'] message = data['body'] plain_message = ('Hello, \n \n There was a new form entry: \n \n') # Include a html template: text_content = plain_message + name + '\n Phone Number: ' + \ phone_number + '\n Email: ' + email + '\n Event Type: ' + event_type + '\n Event Date: ' + event_date + '\n Message: ' + message + '\n - Basking Ridge Form Mail Bot' msg = EmailMultiAlternatives( subject="Basking Ridge Contact Form", body=text_content, to=[ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ], ) # Optional Anymail extensions: msg.track_clicks = True msg.tags = ["Member Inquiry"] messages.success(request, 'Thanks! We will get in touch soon.') # Send it:d msg.send() return redirect("thankyou_static") return render(request, './b_ridge/pages/contact.html', { 'contact_active': True, 'form': form })
def save(self): data = self.cleaned_data u = User.objects.create( email = data.get("primary_email"), first_name = data.get("first_name"), last_name = data.get("last_name"), username = data.get("primary_email").split("@")[0][:30], ) password = User.objects.make_random_password() u.set_password(password) u.save() m = Member.objects.create( user = u, bio = data.get('bio'), phone = data.get('phone'), role = data.get('role'), status = 'pending', photo = data.get('photo') ) #import ipdb; ipdb.set_trace() groups = data.get("groups") for g in groups: g = Group.objects.get(name = g) m.groups.add(g) emails = data.get('secondary_emails'); if emails: for e in emails.split(','): e, created = Email.objects.get_or_create(email = e.strip()) m.secondary_emails.add(e) linkedin = data.get('linkedin') l, created = Profile.objects.get_or_create(url = linkedin, network = 'linkedin') m.profiles.add(l) twitter = data.get('twitter') t, created = Profile.objects.get_or_create(url = twitter, network = 'twitter') m.profiles.add(t) # Send mail to user #import ipdb; ipdb.set_trace() mail_to = settings.ADMIN_EMAIL if settings.DEBUG else data.get("primary_email") msg = EmailMultiAlternatives( subject = "Solicitud de alta", from_email = settings.FROM_EMAIL, to = [mail_to] ) msg.tags = ["iniciador", "alta"] msg.metadata = {'user_id': m.id} msg.template_name = "alta-iniciador" msg.global_merge_vars = { 'NAME': data.get("first_name"), 'PASSWORD': password, 'USERNAME': data.get("primary_email").split("@")[0][:30], #'WEBSITE': "<a href='" + data.get('linkedin') + "/*|TRACKINGNO|*'>Linkedin</a>" } print "Mail sent to:" + mail_to msg.send() # Send mail to iniciador mail_to = settings.ADMIN_EMAIL if settings.DEBUG else settings.FROM_EMAIL msg = EmailMultiAlternatives( subject = "Nueva solicitud de alta", from_email = settings.FROM_EMAIL, to = [mail_to] ) msg.tags = ["iniciador", "alta", "gerencia", "user-" + str(m.id)] msg.metadata = {'user_id': m.id} msg.template_name = "aviso-a-gerencia-alta" msg.global_merge_vars = { 'NAME': data.get("first_name"), 'LASTNAME': data.get("last_name"), 'UID': m.id, 'SERVER': settings.SERVER, #'WEBSITE': "<a href='" + data.get('linkedin') + "/*|TRACKINGNO|*'>Linkedin</a>" } print "Mail sent to:" + mail_to msg.send()
def prepare_email_message(self): """ Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object, depending on whether html_message is empty. """ if get_override_recipients(): self.to = get_override_recipients() if self.template is not None: engine = get_template_engine() subject = engine.from_string(self.template.subject).render(self.context) plaintext_message = engine.from_string(self.template.content).render(self.context) multipart_template = engine.from_string(self.template.html_content) html_message = multipart_template.render(self.context) tags = engine.from_string(self.tags).render(self.context) else: subject = smart_str(self.subject) plaintext_message = self.message multipart_template = None html_message = self.html_message tags = self.tags connection = connections[self.backend_alias or 'default'] if isinstance(self.headers, dict) or self.expires_at: headers = dict(self.headers or {}) if self.expires_at: headers.update({'Expires': self.expires_at.strftime("%a, %-d %b %H:%M:%S %z")}) else: headers = None if html_message: if plaintext_message: msg = EmailMultiAlternatives( subject=subject, body=plaintext_message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, headers=headers, connection=connection) msg.attach_alternative(html_message, "text/html") else: msg = EmailMultiAlternatives( subject=subject, body=html_message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, headers=headers, connection=connection) msg.content_subtype = 'html' if hasattr(multipart_template, 'attach_related'): multipart_template.attach_related(msg) else: msg = EmailMessage( subject=subject, body=plaintext_message, from_email=self.from_email, to=self.to, bcc=self.bcc, cc=self.cc, headers=headers, connection=connection) for attachment in self.attachments.all(): if attachment.headers: mime_part = MIMENonMultipart(*attachment.mimetype.split('/')) mime_part.set_payload(attachment.file.read()) for key, val in attachment.headers.items(): try: mime_part.replace_header(key, val) except KeyError: mime_part.add_header(key, val) msg.attach(mime_part) else: msg.attach(attachment.name, attachment.file.read(), mimetype=attachment.mimetype or None) attachment.file.close() if tags: msg.tags = tags.split(';') print(msg.tags) self._cached_email_message = msg return msg
def handle(self, *args, **options): #context = self.get_context_data(**kwargs) members = Member.objects.exclude(status='inactive').exclude(status='pending') check = [] notify = [] today = date.today() self.stdout.write('DEBUG: %s' % settings.DEBUG) for m in members: d = today - m.last_activity self.stdout.write('%s = %i' % (m.user.username, d.days)) #import ipdb; ipdb.set_trace() if (d.days > 60) & (m.status != 'unknown') & (d.days < 181): m.status = 'unknown' m.save() check.append(m) self.stdout.write('Pedir validacion (%i dias): "%s"' % (d.days, m.user.username)) elif d.days > 180: notify.append(m) self.stdout.write('Notificar a gerencia (180 dias): "%s"' % m.user.username) # Send emails to user that need to validate their data for c in check: mail_to = settings.ADMIN_EMAIL if settings.DEBUG else c.user.email msg = EmailMultiAlternatives( to = [mail_to], from_email = settings.FROM_EMAIL ) groups = [] for g in c.groups.all(): groups.append(g.name) groups = ', '.join(g for g in groups) emails = [c.user.email] for e in c.secondary_emails.all(): emails.append(e.email) emails = ', '.join(e for e in emails) msg.tags = ["iniciador", "check", today] msg.template_name = "checkeo-iniciador" msg.global_merge_vars = { 'NAME': c.user.first_name, 'GROUPS': groups, 'EMAIL': emails, 'PHONE': c.phone, 'WEBSITE': settings.SERVER, 'LINK': 'http://' + settings.SERVER + '/members/revision/' + c.user.username, 'HASH': hashlib.sha224(str(c.last_activity) + str(c.user.id)).hexdigest() } msg.send() response = msg.mandrill_response[0] mandrill_id = response['_id'] #TODO: Terminar la notificacion a la organizacion for n in notify: mail_to = settings.ADMIN_EMAIL if settings.DEBUG else n.user.email msg = EmailMultiAlternatives( to = [mail_to], from_email = settings.FROM_EMAIL ) groups = [] for g in n.groups.all(): groups.append(g.name) groups = ', '.join(g for g in groups) emails = [n.user.email] for e in n.secondary_emails.all(): emails.append(e.email) emails = ', '.join(e for e in emails) msg.tags = ["iniciador", "notify", today] msg.template_name = "notificar-organizador-no-responde" # A Mandrill template name msg.global_merge_vars = { # Content blocks to fill in 'NAME': n.user.first_name, 'LASTNAME': n.user.last_name, 'GROUPS': groups, 'EMAIL': emails, 'PHONE': n.phone, 'WEBSITE': settings.SERVER, 'LINK': 'http://' + settings.SERVER + '/members/revision/' + n.user.username, 'HASH': hashlib.sha224(str(n.last_activity) + str(n.user.id)).hexdigest() } msg.send() response = msg.mandrill_response[0] mandrill_id = response['_id'] #context['notified'] = notify #context['checked'] = check #self.stdout.write('Notificado los miembros "%s"' % poll_id) self.stdout.write('Notificados los miembros')
def send_confirmation_email(self, registration): import os # create context d = ConfirmationEmailView.get_extra_context(registration) c = Context(d) # create html/txt msg_plaintext = render_to_string('registration/confirmation_email.txt', c) msg_html = render_to_string('registration/confirmation_email.html', c) # email settings subject = _('Thanks for signing up!') from_email = "WearHacks Montreal <%s>" % settings.DEFAULT_FROM_EMAIL to = [registration.email] headers = {'Reply-To': _("WearHacks Montreal Team <*****@*****.**>")} # mandrill settings tags = ['registration confirmation'] if settings.DEBUG: tags.append('test') if registration.is_early_bird: tags.append('early bird') else: tags.append('student') metadata = {'order_id': registration.order_id} # ticket ticket_file_path = os.path.join(settings.SITE_ROOT, registration.ticket_file.path) # try: # fn = '' # directory = os.path.join(settings.SITE_ROOT, 'media', 'orders') # if not os.path.exists(directory): # os.makedirs(directory) # fn = os.path.join(directory, registration.order_id + '.html') # with open(fn, 'w') as f: # f.write(msg_html) # except Exception, e: # if fn: # print "Could not write to %s" % (fn) # print 'ERROR: %s' % (str(e)) msg = EmailMultiAlternatives( subject=subject, body=msg_plaintext, from_email=from_email, to=to, reply_to=[from_email], headers=headers # optional extra headers ) msg.attach_alternative(msg_html, "text/html") msg.attach_file(ticket_file_path) msg.tags = tags msg.metadata = metadata if not settings.DEBUG and not ( hasattr(settings, 'FAKE_SEND_EMAIL') and settings.FAKE_SEND_EMAIL): msg.send() else: print 'Registration email at: %s ' % ( reverse('confirmation_email', kwargs={'order_id' : registration.order_id}))
def send(self, to, text_body, html_body=None, subject=None, tags=None, metadata=None, cc=None, bcc=None, headers=None, important=None): """Send the e-mail. :param to: Recipient of the e-mail. :param text_body: Plain text e-mail body. :param html_body: Rich HTML e-mail body. :param subject: Subject. If not provided, the class instance variable will be used. :param tags: list of mandrill tags :param metadata: dict of mandrill metadata :param cc: list of emails this message should be CC'd to :param bcc: list of emails this message should be BCC'd to """ from_combined = '%s <%s>' % ( self.from_name, self.from_email ) if self.from_name else self.from_email cc = cc if cc is not None else self.cc bcc = bcc if bcc is not None else self.bcc headers = headers if headers is not None else self.headers message = EmailMultiAlternatives(subject or self.subject, text_body, from_combined, [to], cc=cc, bcc=bcc, headers=headers) if html_body: message.attach_alternative(html_body, "text/html") # Attach any files. for filename, (data, mime_type) in self.attachments.items(): message.attach(filename, data, mime_type) # Optional Mandrill-specific extensions: if tags: message.tags = tags if metadata: message.metadata = metadata if important is None: important = self.important if important is not None: message.important = important # Send the message. message.send()