def test_attachments(self): email = mail.EmailMessage('Subject', 'Body goes here', '*****@*****.**', ['*****@*****.**']) text_content = "* Item one\n* Item two\n* Item three" email.attach(filename="test.txt", content=text_content, mimetype="text/plain") # Should guess mimetype if not provided... png_content = b"PNG\xb4 pretend this is the contents of a png file" email.attach(filename="test.png", content=png_content) # Should work with a MIMEBase object (also tests no filename)... pdf_content = b"PDF\xb4 pretend this is valid pdf data" mimeattachment = MIMEBase('application', 'pdf') mimeattachment.set_payload(pdf_content) email.attach(mimeattachment) # Attachment type that wasn't supported in early Mandrill releases: ppt_content = b"PPT\xb4 pretend this is a valid ppt file" email.attach(filename="presentation.ppt", content=ppt_content, mimetype="application/vnd.ms-powerpoint") email.send() data = self.get_api_call_data() attachments = data['message']['attachments'] self.assertEqual(len(attachments), 4) self.assertEqual(attachments[0]["type"], "text/plain") self.assertEqual(attachments[0]["name"], "test.txt") self.assertEqual(decode_att(attachments[0]["content"]).decode('ascii'), text_content) self.assertEqual(attachments[1]["type"], "image/png") # inferred from filename self.assertEqual(attachments[1]["name"], "test.png") self.assertEqual(decode_att(attachments[1]["content"]), png_content) self.assertEqual(attachments[2]["type"], "application/pdf") self.assertEqual(attachments[2]["name"], "") # none self.assertEqual(decode_att(attachments[2]["content"]), pdf_content) self.assertEqual(attachments[3]["type"], "application/vnd.ms-powerpoint") self.assertEqual(attachments[3]["name"], "presentation.ppt") self.assertEqual(decode_att(attachments[3]["content"]), ppt_content) # Make sure the image attachment is not treated as embedded: self.assertFalse('images' in data['message'])
def test_send_attaches_anymail_status(self): """ The anymail_status should be attached to the message when it is sent """ # the DEFAULT_RAW_RESPONSE above is the *only* success response SendGrid returns, # so no need to override it here msg = mail.EmailMessage( 'Subject', 'Message', '*****@*****.**', ['*****@*****.**'], ) sent = msg.send() self.assertEqual(sent, 1) self.assertEqual(msg.anymail_status.status, {'queued'}) self.assertUUIDIsValid( msg.anymail_status.message_id) # don't know exactly what it'll be self.assertEqual( msg.anymail_status.recipients['*****@*****.**'].status, 'queued') self.assertEqual( msg.anymail_status.recipients['*****@*****.**'].message_id, msg.anymail_status.message_id) self.assertEqual(msg.anymail_status.esp_response.content, self.DEFAULT_RAW_RESPONSE)
def post(self, request, *args, **kwargs): """ Loop over all users and send emails. """ to_email = request.data.get("email") for user in self.get_users(to_email): current_site = get_current_site(request) site_name = current_site.name if has_perm(user, "users.can_change_password") or has_perm( user, "users.can_manage"): context = { "email": to_email, "site_name": site_name, "protocol": "https" if self.use_https else "http", "domain": current_site.domain, "path": "/login/reset-password-confirm/", "user_id": urlsafe_base64_encode(force_bytes(user.pk)).decode(), "token": default_token_generator.make_token(user), "username": user.get_username(), } body = self.get_email_body(**context) else: # User is not allowed to reset his permission. Send only short message. body = f""" You do not have permission to reset your password at {site_name}. Please contact your local administrator. Your username, in case you've forgotten: {user.get_username()} """ # Send a django.core.mail.EmailMessage to `to_email`. subject = f"Password reset for {site_name}" subject = "".join(subject.splitlines()) from_email = None # TODO: Add nice from_email here. email_message = mail.EmailMessage(subject, body, from_email, [to_email]) email_message.send() return super().post(request, *args, **kwargs)
def send_verification_email(user_id, current_site): user = User.objects.get(id=user_id) refresh = RefreshToken.for_user(user) token = refresh.access_token relative_link = reverse('email-verification') abs_url = 'http://' + current_site + relative_link + "?token=" + str(token) email_body = 'Hi ' + user.username + \ ' Use the link below to verify your email \n' + abs_url data = { 'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email' } with mail.get_connection() as connection: mail.EmailMessage( subject=data['email_subject'], body=data['email_body'], to=[data['to_email']], connection=connection, ).send() return data
def send_mail( subject_line = None, body_text = None, recipient_list = None, activity_type = None, related_object = None, headers = None, raise_on_failure = False, ): """sends email message logs email sending activity and any errors are reported as critical in the main log file related_object is not mandatory, other arguments are. related_object (if given, will be saved in the activity record) if raise_on_failure is True, exceptions.EmailNotSent is raised """ prefix = askbot_settings.EMAIL_SUBJECT_PREFIX.strip() + ' ' try: assert(subject_line is not None) subject_line = prefix + subject_line msg = mail.EmailMessage( subject_line, body_text, django_settings.DEFAULT_FROM_EMAIL, recipient_list, headers = headers ) msg.content_subtype = 'html' msg.send() if related_object is not None: assert(activity_type is not None) except Exception, error: logging.critical(unicode(error)) if raise_on_failure == True: raise exceptions.EmailNotSent(unicode(error))
def build_email(self): assert self.subject assert self.body # add a custom header to resolve the mail ID from bounces/complaints headers = {'X-MID': self.id} if self.user and hasattr(self.user, 'get_unsubscribe_url'): headers['List-Unsubscribe'] = '<{}>'.format( self.user.get_unsubscribe_url()) kwargs = { 'to': [self.to], 'subject': self.subject, 'body': self.body, 'headers': headers, } if self.html_body: email = mail.EmailMultiAlternatives(**kwargs) email.attach_alternative(self.html_body, 'text/html') else: email = mail.EmailMessage(**kwargs) return email
def send_user_remove_mail(email, send_type="user_remove"): email_record = EmailVerifyRecord() code = random_str(16) email_record.code = code email_record.email = email email_record.send_type = 'user_rm' email_record.save() title=u'账号注销通知' connect_url = 'http://www.csinla.com/contactservice/' regist_url = 'http://www.csinla.com/accounts/registerstu/' html = ''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk" /> <title>email</title> </head> <body> <div> <p>尊敬的用户您好</p> <p style="text-indent:2em">因为您长时间未激活注册邮箱,您所注册的账号和相关信息已被删除。对此带来的不便,我们深感抱歉。</p> <p style="text-indent:2em">对于注册未激活的通常原因为: 填写的邮件地址无效,验证邮件在您的垃圾邮箱 如果您遇到其他相关注册问题,请<a href="%s">联系我们客服</a>。您也可以尝试<a href="%s">再次注册</a>。</p> <p style="text-indent:2em">谢谢您的耐心阅读和支持</p> <p>CSinLA Team</p> </div> </body> </html> ''' % (connect_url,regist_url) msg = mail.EmailMessage(title.encode('utf-8'), html, EMAIL_FROM, [email]) msg.content_subtype = 'html' msg.encoding = 'utf-8' #image = add_img(path+str(im.img.url), 'test_cid') #msg.attach(image) if msg.send(): return True else: return False
def test_email_message(self): self.set_mock_response(accepted=6) email = mail.EmailMessage( 'Subject', 'Body goes here', '*****@*****.**', ['*****@*****.**', 'Also To <*****@*****.**>'], bcc=['*****@*****.**', 'Also BCC <*****@*****.**>'], cc=['*****@*****.**', 'Also CC <*****@*****.**>'], headers={'Reply-To': '*****@*****.**', 'X-MyHeader': 'my value', 'Message-ID': '*****@*****.**'}) email.send() params = self.get_send_params() self.assertEqual(params['subject'], "Subject") self.assertEqual(params['text'], "Body goes here") self.assertEqual(params['from_email'], "*****@*****.**") self.assertEqual(params['recipients'], ['*****@*****.**', 'Also To <*****@*****.**>']) self.assertEqual(params['bcc'], ['*****@*****.**', 'Also BCC <*****@*****.**>']) self.assertEqual(params['cc'], ['*****@*****.**', 'Also CC <*****@*****.**>']) self.assertEqual(params['custom_headers'], { 'Reply-To': '*****@*****.**', 'X-MyHeader': 'my value', 'Message-ID': '*****@*****.**'})
def test_send_template(self): msg = mail.EmailMessage('Subject', 'Text Body', '*****@*****.**', ['*****@*****.**']) msg.template_name = "PERSONALIZED_SPECIALS" msg.template_content = { 'HEADLINE': "<h1>Specials Just For *|FNAME|*</h1>", 'OFFER_BLOCK': "<p><em>Half off</em> all fruit</p>" } msg.send() self.assert_mandrill_called("/messages/send-template.json") data = self.get_api_call_data() self.assertEqual(data['template_name'], "PERSONALIZED_SPECIALS") # Djrill expands simple python dicts into the more-verbose name/content # structures the Mandrill API uses self.assertEqual(data['template_content'], [{ 'name': "HEADLINE", 'content': "<h1>Specials Just For *|FNAME|*</h1>" }, { 'name': "OFFER_BLOCK", 'content': "<p><em>Half off</em> all fruit</p>" }])
def test_comma_in_display_name(self): # note there are two paths: with cc/bcc, and without msg = mail.EmailMessage( 'Subject', 'Message', '"Example, Inc." <*****@*****.**>', ['"Recipient, Ltd." <*****@*****.**>']) msg.send() data = self.get_api_call_json() self.assertEqual(data['FromName'], 'Example, Inc.') self.assertEqual(data['FromEmail'], '*****@*****.**') self.assertEqual(data['Recipients'][0]["Email"], "*****@*****.**") self.assertEqual(data['Recipients'][0]["Name"], "Recipient, Ltd.") # separate Name field works fine # Mailjet 3.0 API doesn't properly parse RFC-2822 quoted display-names from To/Cc/Bcc: # `To: "Recipient, Ltd." <*****@*****.**>` tries to send messages to `"Recipient` # and to `Ltd.` (neither of which are actual email addresses). # As a workaround, force MIME "encoded-word" utf-8 encoding, which gets past Mailjet's broken parsing. # (This shouldn't be necessary in Mailjet 3.1, where Name becomes a separate json field for Cc/Bcc.) msg.cc = ['*****@*****.**'] msg.send() data = self.get_api_call_json() # self.assertEqual(data['To'], '"Recipient, Ltd." <*****@*****.**>') # this doesn't work self.assertEqual(data['To'], '=?utf-8?q?Recipient=2C_Ltd=2E?= <*****@*****.**>') # workaround
def get(self, request): try: mail_connection = mail.get_connection() emailx = mail.EmailMessage( 'Hello1111111111', 'Body goes here111111', "*****@*****.**", ['*****@*****.**'], ) emailx.send() emails = [] for i in range(0, 30): email = copy.copy(emailx) email.subject = "subject" + str(i) email.connection = mail_connection emails.append(email) # send_mails.delay(mail_connection,emails) return Response(status=200) except Exception as e: print(e) traceback.print_exc() return Response(status=400)
def send_email(to_address, from_address, subject, message): """Try to send an email -> (bool_success, str_status_message)""" if False in [bool(i) for i in to_address]: return (False, "No 'to' address") return_message = "" success = False try: mess = mail.EmailMessage(subject, message, from_address, to_address) mess.send() return_message = mess success = True except smtplib.SMTPException as e: return_message = e except socket.error as e: # catch this everything because of http://bugs.python.org/issue2118 return_message = e return (success, return_message)
def test_email_message(self): email = mail.EmailMessage( 'Subject', 'Body goes here', '*****@*****.**', ['*****@*****.**', 'Also To <*****@*****.**>'], bcc=['*****@*****.**', 'Also BCC <*****@*****.**>'], cc=['*****@*****.**', 'Also CC <*****@*****.**>'], headers={'Reply-To': '*****@*****.**', 'X-MyHeader': 'my value', 'Message-ID': '*****@*****.**'}) # should override backend msgid email.send() data = self.get_api_call_json() self.assertEqual(data['subject'], "Subject") self.assertEqual(data['plain_body'], "Body goes here") self.assertEqual(data['from'], "*****@*****.**") self.assertEqual(data['to'], ['*****@*****.**', 'Also To <*****@*****.**>']) self.assertEqual(data['bcc'], ['*****@*****.**', 'Also BCC <*****@*****.**>']) self.assertEqual(data['cc'], ['*****@*****.**', 'Also CC <*****@*****.**>']) self.assertEqual(data['reply_to'], '*****@*****.**') self.assertCountEqual(data['headers'], { 'Message-ID': '*****@*****.**', 'X-MyHeader': 'my value' })
def test_send_multiple_emails(self): N = 10 msgs = [mail.EmailMessage(subject="msg %d" % i) for i in range(N)] tasks.send_emails([email_to_dict(msg) for msg in msgs], backend_kwargs={'foo': 'bar'}) # Assert that only "odd"/good messages have been sent. self.assertEqual(len(mail.outbox), 5) self.assertEqual( [msg.subject for msg in mail.outbox], ["msg 1", "msg 3", "msg 5", "msg 7", "msg 9"] ) # Assert that "even"/bad messages have been requeued, # one retry task per bad message. self.assertEqual(len(self._retry_calls), 5) odd_msgs = [msg for idx, msg in enumerate(msgs) if even(idx)] for msg, (args, kwargs) in zip(odd_msgs, self._retry_calls): retry_args = args[0] self.assertEqual(retry_args, [[email_to_dict(msg)], {'foo': 'bar'}]) self.assertTrue(isinstance(kwargs.get('exc'), RuntimeError)) self.assertFalse(kwargs.get('throw', True))
def check_email(app_configs, **kwargs): errors = [] # Check for debug-ish email backends if settings.EMAIL_BACKEND in [ 'django.core.mail.backends.console.EmailBackend', 'django.core.mail.backends.filebased.EmailBackend', 'django.core.mail.backends.locmem.EmailBackend', ]: errors.append(E001) # So we assume if you set the dummy backend, you are not interested in mail, # otherwise you would have used on of the other ones to actually see mails # being sent. if settings.EMAIL_BACKEND != 'django.core.mail.backends.dummy.EmailBackend': # Check if we can send email. We just check if the mechanism works, we # can not detect if the backend fails after we send it (delayed # refusals). # noinspection PyBroadException try: connection = mail.get_connection(fail_silently=False) mail.EmailMessage(to=['*****@*****.**'], subject='Test message', body='Test message', connection=connection).send(fail_silently=False) except: # Catch all since we do not care about backend at this point errors.append(W001) if settings.DEFAULT_FROM_EMAIL.endswith('@localhost'): errors.append(E002) if settings.SERVER_EMAIL == 'root@localhost': errors.append(I001) # TODO: check spammy-ness of our e-mails return errors
def send_emails(subject, content, recipients=None, request=None, content_subtype='html'): # Get common context ctx = _get_context(request) # Get sender sender = ctx['sender'] if ctx.get( 'sender') else '"Default sender name" <*****@*****.**>' # Get recipients if not recipients: # Send emails to managers if no email is given recipients = [a[1] for a in settings.MANAGERS] elif not isinstance(recipients, (tuple, list)): recipients = [recipients] # Prepare emails messages connection = None sent = list() error = 'no recipient' for recipient in recipients: msg = mail.EmailMessage(subject.encode('utf-8'), content.encode('utf-8'), sender, [recipient]) msg.content_subtype = content_subtype # by default, set email content type to html try: if not connection: connection = mail.get_connection() connection.send_messages([msg]) except Exception, e: error = e logger.error('Error when trying to send email to: %s.\n%s' % (recipient, traceback.format_exc())) else: sent.append(recipient[recipient.index('<') + 1:].rstrip('> ') if '<' in recipient else recipient) logger.info(u'Mail with subject "%s" sent to "%s".', subject, recipient)
def test_name_addr(self): """Make sure RFC2822 name-addr format (with display-name) is allowed (Test both sender and recipient addresses) """ msg = mail.EmailMessage( 'Subject', 'Message', 'From Name <*****@*****.**>', ['"Recipient, #1" <*****@*****.**>', '*****@*****.**'], cc=['Carbon Copy <*****@*****.**>', '*****@*****.**'], bcc=['Blind Copy <*****@*****.**>', '*****@*****.**']) msg.send() data = self.get_api_call_json() self.assertEqual(len(data['Messages']), 1) message = data['Messages'][0] self.assertEqual(data['Globals']['From'], { "Email": "*****@*****.**", "Name": "From Name" }) self.assertEqual(message['To'], [{ "Email": "*****@*****.**", "Name": "Recipient, #1" }, { "Email": "*****@*****.**" }]) self.assertEqual(data['Globals']['Cc'], [{ "Email": "*****@*****.**", "Name": "Carbon Copy" }, { "Email": "*****@*****.**" }]) self.assertEqual(data['Globals']['Bcc'], [{ "Email": "*****@*****.**", "Name": "Blind Copy" }, { "Email": "*****@*****.**" }])
def do(self): print "Going to execute cron: TestEmailsCron..." print "https://github.com/CICIC/gestioCI/blob/master/cron.py#L11" yNotifications = Email() yNotifications.subject = "Test GestioCI" yNotifications.body = "Testing Django GestioCI Email server" yNotifications.efrom = "*****@*****.**" yNotifications.to_list = ["*****@*****.**", "*****@*****.**"] print "Method 1" # from django.core.mail import send_mail # print send_mail(yNotifications.subject, yNotifications.body, yNotifications.efrom, yNotifications.to_list) print "Method 2" connection = mail.get_connection() print "conection getted" print "HOST: " + connection.host print "PORT: " + str( connection.port ) print "USER: "******"PASS: "******"TLS: " + str ( connection.use_tls ) print connection.open() print "connaction opened" print "Sending" oneemail = mail.EmailMessage(yNotifications.subject, yNotifications.body, yNotifications.efrom, yNotifications.to_list(), connection=connection ) print oneemail.send() print "Closing connection" connection.close()
def schedule(): elligible = [app for app in Application.objects.filter(year=2011, provisional=False, organization__constituency_group__name__startswith="Honor").order_by('organization__name') if app.approved()] ''' for x in xrange(len(elligible)): if elligible[x].organization.name.startswith("International Student"): y = elligible.pop(x) elligible.append(y) break''' # generate emails emails = [] time = START_TIME for app in elligible: print "%s %s %s" % (app.organization, time.date().isoformat(), time.time().isoformat()) email = app.email("AFAP Hearing (%s)" % (app.organization.name), template.render( Context({'organization':app.organization, 'datetime': time, 'location': LOCATION, 'constituency_group': app.organization.constituency_group})), 'EMAILREMOVED', True) emails.append((app.organization.name, mail.EmailMessage(*email))) #time += DELTA print for (org, email) in emails: print email.message() print conn = mail.get_connection() conn.open() for (org, email) in emails: print "sending email to %s" % (org,) conn.send_messages((email,)) conn.close()
def _send_email(obj, mails): send_ok = False with mail.get_connection() as connection: message = mail.EmailMessage(obj.subject, obj.message, settings.DEFAULT_FROM_EMAIL, mails, connection=connection) message.content_subtype = "html" if obj.file: message.attach_file(settings.MEDIA_ROOT + obj.file.name) try: message.send() send_ok = True except: obj.problems = True obj.save() if send_ok: obj.sended = True obj.queued = False obj.problems = False obj.save()
def test_custom_headers(self): self.set_mock_result(accepted=6) email = mail.EmailMessage('Subject', 'Body goes here', '*****@*****.**', ['*****@*****.**'], cc=['*****@*****.**'], headers={ 'Reply-To': '*****@*****.**', 'X-MyHeader': 'my value', 'Message-ID': '*****@*****.**' }) email.send() data = self.get_api_call_json() self.assertEqual( data["content"]["headers"], { # Reply-To moved to separate param (below) "X-MyHeader": "my value", "Message-ID": "*****@*****.**", "Cc": "*****@*****.**", # Cc header added }) self.assertEqual(data["content"]["reply_to"], "*****@*****.**")
def test_name_addr(self): """Make sure RFC2822 name-addr format (with display-name) is allowed (Test both sender and recipient addresses) """ msg = mail.EmailMessage( 'Subject', 'Message', 'From Name <*****@*****.**>', ['Recipient #1 <*****@*****.**>', '*****@*****.**'], cc=['Carbon Copy <*****@*****.**>', '*****@*****.**'], bcc=['Blind Copy <*****@*****.**>', '*****@*****.**']) msg.send() data = self.get_api_call_json() # See https://dev.mailjet.com/guides/#sending-a-basic-email self.assertEqual(data['FromName'], 'From Name') self.assertEqual(data['FromEmail'], '*****@*****.**') self.assertEqual(data['To'], 'Recipient #1 <*****@*****.**>, [email protected]') self.assertEqual(data['Cc'], 'Carbon Copy <*****@*****.**>, [email protected]') self.assertEqual(data['Bcc'], 'Blind Copy <*****@*****.**>, [email protected]')
def create_mail_message(remind, extra_title): recipients = [] for recipient in remind.receivers.all(): recipients.append(recipient.email) if remind.extra_recipient: recipients.append(remind.extra_recipient) _subject = extra_title + remind.title _message = u"【提醒内容】: %s" % remind.content _message += u"\r\n【提醒方式】: %s" % remind.get_remind_method_display() if remind.remind_method=="DEADLINE": _message+="\r\n【Deadline】: %s" % timezone.localtime(remind.deadline_time).strftime("%Y-%m-%d %H:%M") elif remind.remind_method=="PERD": _message+="\r\n【首次提醒】: %s" % timezone.localtime(remind.first_remind_time).strftime("%Y-%m-%d %H:%M") _message+="\r\n【提醒频度】: %s" % remind.get_interval_description() _message+="\r\n【过期时间】: %s" % timezone.localtime(remind.expire_time).strftime("%Y-%m-%d %H:%M") elif remind.remind_method=="ONETIME": _message+="\r\n【提醒时间】: %s" % timezone.localtime(remind.remind_time).strftime("%Y-%m-%d %H:%M") _message+="\r\n【创建人员】: %s" % remind.create_user.email _message+="\r\n\r\n来自SDL SaaS在线邮件提醒\r\nhttp://saas.janusec.com" mail_message=mail.EmailMessage(subject=_subject, body=_message, from_email=pmp.settings.EMAIL_FROM, to=recipients, cc=[remind.create_user.email], reply_to=[remind.create_user.email]) return mail_message
def email_to_rider(populaire_pk, rider_pk, host): """Send pre-registration confirmation email to rider. """ populaire = Populaire.objects.get(pk=populaire_pk) rider = Rider.objects.get(pk=rider_pk) pop_page = reverse( 'populaires:populaire', args=(populaire.short_name, populaire.date.strftime('%d%b%Y'))) pop_page_url = 'http://{0}{1}'.format(host, pop_page) from_randopony = EmailAddress.objects.get(key='from_randopony').email email = mail.EmailMessage( subject='Pre-registration Confirmation for {0}'.format(populaire), body=render_to_string( 'populaires/email/to_rider.txt', {'populaire': populaire, 'pop_page_url': pop_page_url}), from_email=from_randopony, to=[rider.email], headers={ 'Sender': from_randopony, 'Reply-To': populaire.organizer_email} ) email.send()
def test_name_addr(self): """Make sure RFC2822 name-addr format (with display-name) is allowed (Test both sender and recipient addresses) """ msg = mail.EmailMessage( 'Subject', 'Message', 'From Name <*****@*****.**>', ['Recipient #1 <*****@*****.**>', '*****@*****.**'], cc=['Carbon Copy <*****@*****.**>', '*****@*****.**'], bcc=['Blind Copy <*****@*****.**>', '*****@*****.**']) msg.send() data = self.get_api_call_json() self.assertEqual(data['message']['from_name'], "From Name") self.assertEqual(data['message']['from_email'], "*****@*****.**") self.assertEqual(data['message']['to'], [ {'email': '*****@*****.**', 'name': 'Recipient #1', 'type': 'to'}, {'email': '*****@*****.**', 'name': '', 'type': 'to'}, {'email': '*****@*****.**', 'name': 'Carbon Copy', 'type': 'cc'}, {'email': '*****@*****.**', 'name': '', 'type': 'cc'}, {'email': '*****@*****.**', 'name': 'Blind Copy', 'type': 'bcc'}, {'email': '*****@*****.**', 'name': '', 'type': 'bcc'}, ])
def send_emails(subject, recipients, plaintext, html): """ Send individual e-mails to each user in the list of recipients with the subject as `subject`, and the body as `plaintext` and `html`. """ conn = mail.get_connection() conn.open() emails = [] for recipient in recipients: context = {"user": recipient} html = _render_template_with_context(html, context) if plaintext is None: email = mail.EmailMessage(subject, html, to=[recipient.email]) email.content_subtype = "html" else: plaintext = _render_template_with_context(plaintext, context) email = mail.EmailMultiAlternatives(subject, plaintext, to=[recipient.email]) email.attach_alternative(html, "text/html") emails.append(email) conn.send_messages(emails) conn.close()
def block_users(self, request, queryset): self.message_user(request, "Blocked {} users".format(queryset.count())) connection = mail.get_connection() connection.open() for obj in queryset: if not obj.blocked: html_message = loader.render_to_string( 'accounts/blocked.html', {'user_name': obj.user_name}) html_message = strip_tags(html_message) obj.blocked = True [ s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == str(obj.id) ] obj.save() email = mail.EmailMessage( 'חסימה מאתר B7Fun', html_message, '*****@*****.**', [obj.email], connection=connection, ) email.send()
def test_send_without_to_attaches_anymail_status(self): """The anymail_status should be attached even if there are no `to` recipients""" response_content = b"""{ "status": "success", "time": 1.08, "flags": {}, "data": { "message_id": "*****@*****.**", "messages": { "*****@*****.**": { "id": 1531, "token": "xLcafDRCVUFe" } } } }""" self.set_mock_response(raw=response_content) msg = mail.EmailMessage('Subject', 'Message', '*****@*****.**', cc=['*****@*****.**'],) sent = msg.send() self.assertEqual(sent, 1) self.assertEqual(msg.anymail_status.status, {'queued'}) self.assertEqual(msg.anymail_status.message_id, 1531) self.assertEqual(msg.anymail_status.recipients['*****@*****.**'].status, 'queued') self.assertEqual(msg.anymail_status.recipients['*****@*****.**'].message_id, 1531) self.assertEqual(msg.anymail_status.esp_response.content, response_content)
def user_password_reset(request): reset_form = forms.UserPasswordResetForm() if request.method == 'POST': reset_form = forms.UserPasswordResetForm(request.POST) if reset_form.is_valid(): email = reset_form.data['email'] user_object = User.objects.get(email=email) encrypted_username = computeMD5Hash(user_object.username) normal_user_object = models.NormalUser.objects.get(user_id=user_object.id) normal_user_object.email_validation_code = encrypted_username normal_user_object.save() current_site = get_current_site(request) html_content = render_to_string('registration/password_reset_email.html', { 'username': encrypted_username, 'first_name': user_object.first_name, 'last_name': user_object.last_name, 'domain': current_site.domain}) text_content = strip_tags(html_content) connection = mail.get_connection() connection.open() email1 = mail.EmailMessage( 'Confirm your account on Social site', text_content, '*****@*****.**', [email], connection=connection ) email1.send() connection.close() return render(request, 'registration/password_reset_email_sent.html', {'first_name': user_object.first_name, 'last_name': user_object.last_name}) else: return render(request, 'registration/password_reset_form.html', {'reset_form': reset_form}) else: return render(request, 'registration/password_reset_form.html', {'reset_form': reset_form})
def check_todojob(): now = datetime.now().strftime("%Y-%m-%d") data = TodoJob.objects.filter(status=1).values('project_name', 'project_title', 'manager', 'deadline_time', 'project_type') for d in data: remarks = "" if d['deadline_time'].strftime("%Y-%m-%d") == now: to_mail = [] if d['manager'] == 'sawyer': to_mail.append('*****@*****.**') else: to_mail.append(d['manager']+'@21kunpeng.com') if d['project_type'] == 0: project_type = '公共类' else: project_type = '项目单独' content = '项目名称:' + str(d['project_name']) + ' ' + '标题:' + str(d['project_title']) + ' ' + '截止时间:' +\ str(d['deadline_time'].strftime("%Y-%m-%d")) + ' ' + '类型:' + str(project_type) remarks += "平台链接:<a href='http://124.93.223.118:65534/'>http://124.93.223.118:65534/</a><br/><br/>\ <strong><font color='blue'>本邮件由系统自动发送</font></strong><br/>" html = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <strong><font color='red'>您有一个待跟进工作即将到期,请登录平台查看</font></strong><br/> <br/>''' + content + '''<br/><br/> 备注说明:<br/>''' + remarks + ''' </body> </html> ''' msg = mail.EmailMessage("您有一个待跟进工作即将到期,请登录平台查看", html, settings.EMAIL_HOST_USER, to_mail) msg.content_subtype = 'html' msg.encoding = 'utf-8' msg.send()