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 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_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_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 mail_guest(self, subject, body): msg = EmailMultiAlternatives(subject, '', None, [self.email, ]) msg.attach_alternative(body, "text/html") msg.track_opens = True msg.track_clicks = True msg.auto_text = True 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_html_mail(subject, message, from_email, recipient_list, connection=None): msg = EmailMultiAlternatives(subject=subject, body=message, from_email=from_email, to=recipient_list, connection=connection) msg.attach_alternative(message, "text/html") msg.track_opens = True msg.track_clicks = True msg.auto_text = True 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, subject=None, body=None, sg_template_on=False, sg_template=None, template=None, campaign=None): from anymail.message import AnymailMessage from django.core.mail import send_mail, EmailMultiAlternatives from django.utils.html import strip_tags if template is not None: try: html_content = render_to_string( f"contact_management/{template}", self.__dict__) except: html_content = None note = template else: html_content = None note = body if html_content is not None: plain_content = strip_tags(html_content) else: plain_content = body message = EmailMultiAlternatives(subject, plain_content, DEFAULT_FROM_EMAIL, [self.email]) if sg_template_on == True: message.template_id = sg_template template = sg_template message.metadata = { "account_id": self.account_name, "contact_id": self.id, "template": template, "campaign": campaign, "email_source": "VCM", "contact_type": "LEAD", "FIRST_NAME": self.first_name, "LAST_NAME": self.last_name, "ACCOUNT_NAME": self.account_name, 'DATETIME': datetime.now().isoformat() } if html_content is not None: message.attach_alternative(html_content, "text/html") message.track_clicks = True message.track_opens = True try: message.send() status = message.anymail_status status.message_id n = Note(lead=self, date=datetime.now(), note=note, follow_up_date=datetime.now() + timedelta(days=14), contact_type='EMAIL') n.save() print(f"email sent to {self}") except: print('message did not send to', self)
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_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_htmlmail(from_email, to, cc=None, bcc=None, subject="", html_body=""): """ Send HTML and plain text mail """ text_plain = strip_tags(html_body) logger.info(f'>>>> send_htmlmail {subject} to {to}') msg = EmailMultiAlternatives(from_email=from_email, to=[to], cc=cc, bcc=bcc, subject=subject, body=text_plain) # AnyMail attributes msg.track_opens = True msg.track_clicks = True msg.attach_alternative(html_body, "text/html") 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_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_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(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_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 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 send_email(self, subject=None, body=None, sg_template_on=False, sg_template=None, template=None, campaign=None): from anymail.message import AnymailMessage from django.core.mail import send_mail, EmailMultiAlternatives from django.utils.html import strip_tags if template is not None: try: html_content = render_to_string( f"contact_management/{template}", self.__dict__) except: html_content = None note = template else: html_content = None note = body if html_content is not None: plain_content = strip_tags(html_content) else: plain_content = body message = EmailMultiAlternatives(subject, plain_content, DEFAULT_FROM_EMAIL, [self.email]) if sg_template_on == True: message.template_id = sg_template template = sg_template note = f"SENDGRID TEMPLATE {sg_template}" message.metadata = { "account_id": self.account.id, "contact_id": self.id, "template": template, "campaign": campaign, "email_source": "VCM", "contact_type": "CONTACT", "FIRST_NAME": self.first_name, "LAST_NAME": self.last_name, "ACCOUNT_NAME": self.account.name, 'DATETIME': datetime.now().isoformat(), } if html_content is not None: message.attach_alternative(html_content, "text/html") message.track_clicks = True message.track_opens = True try: print('we are here') print(template) message.send() print('we just sent??') status = message.anymail_status status.message_id print(status.message_id, 'MID!!') n = Note(contact=self, date=datetime.now(), note=note, follow_up_date=datetime.now() + timedelta(days=14), contact_type='EMAIL') print(n, 'NOTE') n.save() print(n.follow_up_date, 'NOTE SAVED') except Exception as errors: print(errors, 'this is the erro!') print('message did not send to', self)