def sender(template_name, to=None, cc=None, bcc=None, attach_files=[], **kvp): try: tmpl = Mail.objects.get(template_name=template_name) except Mail.DoesNotExist: return if to and cc: for v in to: try: cc.remove(v) except ValueError: continue if to and bcc: for v in to: try: bcc.remove(v) except ValueError: continue subject = tmpl.subject.format(**kvp) body = PartialFormatter().format(tmpl.message, **kvp) from_email = DEFAULT_FROM_EMAIL connection = get_connection(fail_silently=False) mail = EmailMultiAlternatives( subject=subject, body=body, from_email=from_email, to=to, cc=cc, bcc=bcc, connection=connection) for attach_file in attach_files: mail.attach_file(attach_file) mail.send()
def make_mail(ModelAdmin, request, queryset): """ Создаем рассылку и отправляем. """ from datetime import datetime if queryset.filter(status='n'): connection = mail.get_connection() connection.open() messages = list() for i in xrange(0, len(get_recipients(queryset))): rep_list = get_recipients(queryset) header = u'\'' + get_sender(queryset) + u'\'' msg = EmailMultiAlternatives( subject = unicode(get_subject(queryset)), body = unicode(get_body(queryset)), from_email = unicode(get_fullname(queryset)), to = [rep_list[i]], # attachments=unicode(get_attachment(queryset)), reply_to = [unicode(get_fullname(queryset))]) msg.attach_alternative(unicode(get_body(queryset)), 'text/html') # msg.attach_file(get_attachment(queryset)) msg.attach_file(os.path.join(settings.MEDIA_ROOT, str(get_attachment(queryset)))) msg.encoding = 'utf-8' messages.append(msg) connection.send_messages(messages) connection.close() ModelAdmin.message_user(request, u'Рассылка отправлена') # ModelAdmin.message_user(request, get_attachment(queryset)) queryset.update(status='f') queryset.update(send_date=datetime.now()) else: ModelAdmin.message_user(request, u'Рассылка уже выполняется или завершена', 'warning')
def common_send_email(subject, text_template_path, html_template_path, context_data, recipients, from_email=None): """ This method is a common method to send email via the bhane system. """ coupon_obj = context_data['coupon_obj'] if not from_email: from_email = DEFAULT_FROM_EMAIL #get templates from file system text_raw_content = get_template(text_template_path) try: html_raw_content = get_template(coupon_obj.vendor.email_content.path)#will return absolute path except: html_raw_content = get_template(html_template_path)#else pickup common_vendor_email.html #render the raw data in the template d = Context(context_data) text_content = text_raw_content.render(d) html_content = html_raw_content.render(d) #contstruct the message and send it msg = EmailMultiAlternatives(subject, text_content, from_email, recipients) if coupon_obj.image.name: msg.attach_file(coupon_obj.image.path) msg.attach_alternative(html_content, "text/html") msg.send()
def task_send_invoice(invoice): urlsafe_token = invoice.generate_token() subject = "Presupuesto" from_email = settings.ADMIN_EMAIL to = invoice.proposal.event.customer.email template = loader.get_template("base/email/invoice.html") domain = settings.CATERFULL_BASE_URL context = Context({'token':urlsafe_token,'domain':domain, 'invoice':invoice, 'iidb64':urlsafe_base64_encode(force_bytes(invoice.id))}) text_content = template.render(context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) invoice_pdf = generate_invoice_pdf(invoice=invoice) msg.content_subtype = "html" msg.attach_file(invoice_pdf.name,'application/pdf') response = OK try: with transaction.atomic(): if not invoice.has_payment_order(): payment = create_payment(invoice.proposal.get_total()) invoice.set_payment(payment=payment) msg.send(fail_silently=False) invoice.has_been_sent() except SMTPException as e: print(e) invoice.reset_token() response = ERROR except Exception as e: invoice.reset_token() response = ERROR print(e) return response
def send_raw_mail(self, to_addrs, subject, html, attachfile_paths=None): """ send mail with attachments. charset depend on CHARSET in settings.py. if not set, default is utf8. Args: to_addrs (list): email address list subject (string): subject string html (string): html mail content attachfile_paths (list): a list contains all the attachments path want to send. if this arg is None, will use self.send_mail to send an email """ if not attachfile_paths: logger.warn('use send_raw_mail method but with no attachment. to %s, subject: %s' % ( to_addrs, subject )) self.send_html_mail(to_addrs, subject, html) return logger.info('start to send raw mail to %s, subject: %s' % (to_addrs, subject)) email = EmailMultiAlternatives(subject, html, self.from_addr, to_addrs) email.content_subtype = 'html' for attachment_path in attachfile_paths: email.attach_file(attachment_path) if not email.send(): error_msg = 'mail send to nobody. subject: %s, toAddrs: %s' % (subject, to_addrs) logger.error(error_msg) raise Exception(error_msg) logger.info('successfully send raw mail to %s, subject: %s' % (to_addrs, subject))
def send_email(subject, template_name, context, from_email=settings.EMAIL_HOST_USER, receipts=None, file_path=None, file_name=None, file_content=None, mime_type=None): from django.core.mail.message import EmailMultiAlternatives from django.core.mail import DEFAULT_ATTACHMENT_MIME_TYPE from django.template.loader import render_to_string from django.utils.html import strip_tags if receipts is None: receipts = [] email_message_html = render_to_string(template_name, context=context) email_message_plaintext = strip_tags(email_message_html) email = EmailMultiAlternatives(subject=subject, body=email_message_plaintext, from_email=from_email, to=receipts) email.attach_alternative(email_message_html, 'text/html') if file_path: email.attach_file(file_path, mimetype=DEFAULT_ATTACHMENT_MIME_TYPE) if file_content: email.attach(filename=file_name, content=file_content, mimetype=mime_type) email.send()
def task_send_proposal(proposal, old_status=None): urlsafe_token = proposal.generate_token() subject = "Presupuesto" from_email = settings.ADMIN_EMAIL to = proposal.event.customer.email template = loader.get_template("base/email/proposal.html") domain = settings.CATERFULL_BASE_URL context = Context({ 'token': urlsafe_token, 'domain': domain, 'proposal': proposal, 'pidb64': urlsafe_base64_encode(force_bytes(proposal.id)) }) html_content = template.render(context) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.content_subtype = "html" # msg.attach_alternative(html_content, "text/html") proposal_pdf = generate_proposal_pdf(proposal=proposal) msg.attach_file(proposal_pdf.name, 'application/pdf') try: msg.send(fail_silently=False) # proposal.has_been_sent() return OK except SMTPException as e: proposal.reset_token(restart_status=True, old_status=old_status) return ERROR
def send_email(self, filename): # send email email = EmailMultiAlternatives(subject='[Olympia GnosisDB backup]', body='GnosisDB backup attached.', from_email=settings.SERVER_EMAIL, to=[a[1] for a in settings.ADMINS]) email.attach_file(filename) email.send()
def sender(template_name, to=None, cc=None, bcc=None, attach_files=[], **kvp): try: tmpl = Mail.objects.get(template_name=template_name) except Mail.DoesNotExist: return if to and cc: for v in to: try: cc.remove(v) except ValueError: continue if to and bcc: for v in to: try: bcc.remove(v) except ValueError: continue subject = tmpl.subject.format(**kvp) body = PartialFormatter().format(tmpl.message, **kvp) from_email = DEFAULT_FROM_EMAIL connection = get_connection(fail_silently=False) mail = EmailMultiAlternatives(subject=subject, body=body, from_email=from_email, to=to, cc=cc, bcc=bcc, connection=connection) for attach_file in attach_files: mail.attach_file(attach_file) if ENABLE_SENDING_MAIL: try: mail.send() except Exception as e: logger.exception(e) # Activer l'exception lorsque gérée par l'application. # return MailError() else: logger.warning("Sending mail is disable.")
def send_mail(subject, text_content, html_content, to_email_list, attach_file='',DEFAULT_FROM_EMAIL=None): """ |##@函数目的:发送邮件 子函数,要调用请使用上面的 sendmail |##@返回值: |##@函数逻辑:无 |##@开发人:jhuang,rksun |##@时间: |##@参数说明: subject 邮件标题 text_content 邮件正文 html_content HTML版本邮件正文 to_email_list ['*****@*****.**', '*****@*****.**'] send_mail('test','test','test',['*****@*****.**']) """ if isinstance(to_email_list, list) is False and to_email_list != None: lists = [] lists.append(to_email_list) to_email_list = lists try: to_email_list = list(set(to_email_list)) if '' in to_email_list: to_email_list.remove('') # to_email_list.remove(None) if len(to_email_list) > 0: logger.debug('发送邮件至:%s,邮件标题:%s' % (to_email_list, subject)) # http://python.usyiyi.cn/documents/django_182/topics/email.html if html_content != '': text_content = html_content msg = EmailMultiAlternatives(subject, text_content, DEFAULT_FROM_EMAIL, to_email_list) msg.encoding = 'utf-8' if html_content != '': msg.attach_alternative(html_content, "text/html") if os.path.isfile(attach_file): logger.debug('添加附件:%s' % (attach_file)) msg.attach_file(attach_file) msg.send() else: logger.debug('邮件发送目标邮箱列表为空,邮件标题:%s' % (subject)) except: logger.exception('发送邮件失败至:%s' % (to_email_list))
def create_message(self, send_text, send_html): """ Create a message object and return it, or return None if no recipients """ # We need at least one recipient to = self._validate_list(self.to) if not len(to): return None if not send_text and not send_html: return None text = self.get_rendered_text() if send_text else None html = self.get_rendered_html() if send_html else None message = EmailMultiAlternatives( subject=self.subject, from_email=self.get_from_address(), to=to, cc=self._validate_list(self.cc), bcc=self._validate_list(self.bcc), headers=self.headers ) if text: message.body = text if send_html: # Text plus html message.attach_alternative(html, 'text/html') else: # There is no text version, so send it as pure html only message.body = html message.content_subtype = 'html' if self.attachments: for attachment in self.attachments: message.attach_file(attachment) return message
def send(self, request=None, email=None, force=False, file_path=None, \ file_name=None, file_type=None, context=None, **kwargs): # Save a version #import pdb;pdb.set_trace() msg = EmailMultiAlternatives( self.subject, self.body, self.sender, [self.email]) msg.attach_alternative(self.body, 'text/html') try: file_path = context['file']['file_path'] except: pass if file_path: msg.attach_file(file_path) try: return msg.send() except SMTPAuthenticationError as (code, resp): print '\n!! SMTP authenication issue \'%s\': "%s"\n' % (code, resp) raise SMTPAuthenticationError(code)
def send(self, request=None, email=None, force=False, file_path=None, \ file_name=None, file_type=None, context=None, **kwargs): # Save a version #import pdb;pdb.set_trace() msg = EmailMultiAlternatives(self.subject, self.body, self.sender, [self.email]) msg.attach_alternative(self.body, 'text/html') try: file_path = context['file']['file_path'] except: pass if file_path: msg.attach_file(file_path) try: return msg.send() except SMTPAuthenticationError as (code, resp): print '\n!! SMTP authenication issue \'%s\': "%s"\n' % (code, resp) raise SMTPAuthenticationError(code)
def send_player_invite(name, email, uid, trip_name, trip_template, attachments): subject = "You have been selected for {}!".format(trip_name) message = "" from_email = settings.EMAIL_HOST_USER recipient_list = [email] html_message = trip_template html_message = html_message.replace("{{player_name}}", name) html_message = html_message.replace( "{{invitation_link}}", "{}?uid={}".format(settings.APP_URL, uid), ) invitation_email = EmailMultiAlternatives( subject=subject, body="", from_email=from_email, to=recipient_list, reply_to=[from_email], ) invitation_email.attach_alternative(html_message, "text/html") for attachment in attachments: invitation_email.attach_file(attachment.document.path) return invitation_email.send(fail_silently=True) return send_mail( subject=subject, message=message, from_email=from_email, recipient_list=recipient_list, html_message=html_message, fail_silently=True, )
def send_mail( context, template_name, to_email_list, from_email=settings.DEFAULT_FROM_EMAIL, bcc=None, cc=None, file_path=None, ): """ A static method that takes inputs and sends mail & sms """ if bcc is None: bcc = [] subject = render_to_string("{}{}.txt".format(template_name, "sub"), context) message = EmailMultiAlternatives( subject=subject, body=render_to_string("{}{}.txt".format(template_name, "msg"), context), from_email=from_email, to=to_email_list, bcc=bcc, cc=cc, alternatives=[ ( render_to_string("{}{}.html".format(template_name, "msg"), context), "text/html", ), ], ) # attach file if file_path: message.attach_file(file_path) message.send()
def get_old_deposit_transfers_task(): old_transfers = DepositTransferNew.objects.order_by("user", "-created_at") try: book = Workbook() chongzhi_sheet = book.add_sheet('ChongZhi') koukuan_sheet = book.add_sheet('KouKuan') chongzhi_row = 0 koukuan_row = 0 chongzhi_sheet.write(chongzhi_row, 0, u"客户编号") chongzhi_sheet.write(chongzhi_row, 1, u"金额") chongzhi_sheet.write(chongzhi_row, 2, u"单号") chongzhi_sheet.write(chongzhi_row, 3, u"描述") chongzhi_sheet.write(chongzhi_row, 4, u"时间") chongzhi_sheet.write(chongzhi_row, 5, u"货币") koukuan_sheet.write(koukuan_row, 0, u"客户编号") koukuan_sheet.write(koukuan_row, 1, u"金额") koukuan_sheet.write(koukuan_row, 2, u"单号") koukuan_sheet.write(koukuan_row, 3, u"描述") koukuan_sheet.write(koukuan_row, 4, u"时间") koukuan_sheet.write(koukuan_row, 5, u"货币") koukuan_sheet.write(koukuan_row, 6, u"已扣金额") koukuan_sheet.write(koukuan_row, 7, u"申报应付金额") koukuan_sheet.write(koukuan_row, 8, u"库房应付金额") koukuan_sheet.write(koukuan_row, 9, u"计费重量") koukuan_sheet.write(koukuan_row, 10, u"申报重量") koukuan_sheet.write(koukuan_row, 11, u"申报长度") koukuan_sheet.write(koukuan_row, 12, u"申报宽度") koukuan_sheet.write(koukuan_row, 13, u"申报高度") koukuan_sheet.write(koukuan_row, 14, u"库房重量") koukuan_sheet.write(koukuan_row, 15, u"库房长度") koukuan_sheet.write(koukuan_row, 16, u"库房宽度") koukuan_sheet.write(koukuan_row, 17, u"库房高度") chongzhi_row = 1 koukuan_row = 1 for old_transfer in old_transfers: if old_transfer.amount >= 0.01: chongzhi_sheet.write(chongzhi_row, 0, old_transfer.user.userprofile.customer_number) chongzhi_sheet.write(chongzhi_row, 1, round(Decimal(old_transfer.amount), 2)) chongzhi_sheet.write(chongzhi_row, 2, old_transfer.origin) chongzhi_sheet.write(chongzhi_row, 3, old_transfer.ref) chongzhi_sheet.write(chongzhi_row, 4, old_transfer.created_at.strftime("%Y-%m-%d %H:%M:%S")) chongzhi_sheet.write(chongzhi_row, 5, old_transfer.user.userprofile.deposit_currency_type) chongzhi_row += 1 else: koukuan_sheet.write(koukuan_row, 0, old_transfer.user.userprofile.customer_number) koukuan_sheet.write(koukuan_row, 1, round(Decimal(old_transfer.amount), 2)) koukuan_sheet.write(koukuan_row, 2, old_transfer.origin) koukuan_sheet.write(koukuan_row, 3, old_transfer.ref) koukuan_sheet.write(koukuan_row, 4, old_transfer.created_at.strftime("%Y-%m-%d %H:%M:%S")) koukuan_sheet.write(koukuan_row, 5, old_transfer.user.userprofile.deposit_currency_type) try: intl_parcel = IntlParcel.objects.get(yde_number=old_transfer.origin) koukuan_sheet.write(koukuan_row, 6, round(Decimal(intl_parcel.booked_fee or 0), 2)) #logger.error('axxx') koukuan_sheet.write(koukuan_row, 7, round(Decimal(intl_parcel.get_fee() or 0), 2)) # u"申报应付金额") #logger.error('bxxx') try: real_fee=intl_parcel.get_real_fee() except: real_fee=0 koukuan_sheet.write(koukuan_row, 8, round(Decimal(real_fee), 2)) # u"库房应付金额") #logger.error('cxxx') vweight = intl_parcel.length_cm * intl_parcel.width_cm * intl_parcel.height_cm / 6000 real_vweight = intl_parcel.real_length_cm * intl_parcel.real_width_cm * intl_parcel.real_height_cm / 6000 chargeable_weight = max(w for w in [intl_parcel.weight_kg, vweight, intl_parcel.real_weight_kg, real_vweight]) #logger.error('dxxx') koukuan_sheet.write(koukuan_row, 9, round(Decimal(chargeable_weight), 2)) # u"计费重量") koukuan_sheet.write(koukuan_row, 10, round(Decimal(intl_parcel.weight_kg or 0), 2)) # u"申报重量") koukuan_sheet.write(koukuan_row, 11, round(Decimal(intl_parcel.length_cm or 0), 2)) # u"申报长度") koukuan_sheet.write(koukuan_row, 12, round(Decimal(intl_parcel.width_cm or 0), 2)) # u"申报宽度") koukuan_sheet.write(koukuan_row, 13, round(Decimal(intl_parcel.height_cm or 0), 2)) # u"申报高度") koukuan_sheet.write(koukuan_row, 14, round(Decimal(intl_parcel.real_weight_kg or 0), 2)) # u"库房重量") koukuan_sheet.write(koukuan_row, 15, round(Decimal(intl_parcel.real_length_cm or 0), 2)) # u"库房长度") koukuan_sheet.write(koukuan_row, 16, round(Decimal(intl_parcel.real_width_cm or 0), 2)) # u"库房宽度") koukuan_sheet.write(koukuan_row, 17, round(Decimal(intl_parcel.real_height_cm or 0), 2)) # u"库房高度") except IntlParcel.DoesNotExist: try: retoure = DhlRetoureLabel.objects.get(retoure_yde_number=old_transfer.origin) koukuan_sheet.write(koukuan_row, 6, "DHL Retoure") except DhlRetoureLabel.DoesNotExist: koukuan_sheet.write(koukuan_row, 6, "NOOOOOOOOOO") except DhlRetoureLabel.MultipleObjectsReturned: koukuan_sheet.write(koukuan_row, 6, "Retoure Duplicated") except Exception as e: logger.error(e) koukuan_sheet.write(koukuan_row, 6, "%s" % e) except IntlParcel.MultipleObjectsReturned: koukuan_sheet.write(koukuan_row, 6, "Intl Parcel Duplicated") except Exception as e: logger.error(e) logger.error(intl_parcel.yde_number) koukuan_sheet.write(koukuan_row, 6, "%s" % e) koukuan_row += 1 book.save("/tmp/old_transfers.xls") connection = get_connection(username=None, password=None, fail_silently=False) mail = EmailMultiAlternatives(u"Old deposit transfers", "", u'韵达德国分公司 <*****@*****.**>', ["*****@*****.**"], connection=connection) mail.attach_file("/tmp/old_transfers.xls") mail.send() #return HttpResponse() except Exception as e: logger.error("%s" % e)