def email(self): id = self.request.matchdict['id'] test = Tests.by({'id':id,'alias':self.request.user.alias}).first() if not test: raise HTTPForbidden() file = self._generate_pdf(id) self.response['id'] = id self.response['emails'] = self.request.params.get('email.addresses',None) if 'form.submitted' in self.request.params: if self.request.params['email.ok'] == '1': emails = self.request.params['email.addresses'].replace(' ','').split(',') for email in emails: if not Validate.email(email): self.notify('Invalid email address',warn=True) return self.template('email.pt') try: message = Message(subject=self._email_fmt(id, str(Properties.get('MAILER_TO_SUBJECT','Submission'))), sender=str(Properties.get('MAILER_GLOBAL_FROM_ADDRESS','System')), recipients=emails, body=self._email_fmt(id, str(Properties.get('MAILER_BODY','Submission')))) attachment = Attachment('submission_' + str(id) + '.pdf', 'application/pdf', file) message.attach(attachment) mailer = get_mailer(self.request) mailer.send(message) self.notify('Email sent!') except Exception as e: print "ERROR: " + str(e) self.notify('Unable to send email!',warn=True) else: self.notify('Unable to send example email!',warn=True) return self.template('email.pt')
def create_message(request, template, context, subject, recipients, attachments=None, extra_headers=None): text_body = render(template + '.txt', context, request=request) # chamaleon txt templates are rendered as utf-8 bytestrings text_body = text_body.decode('utf-8') html_body = render(template + '.pt', context, request=request) extra_headers = extra_headers or {} message = Message( subject=subject, recipients=recipients, body=text_body, html=html_body, extra_headers=extra_headers, ) if attachments is not None: for attachment in attachments: message.attach(attachment) return message
def test_attach(self): from pyramid_mailer.message import Message from pyramid_mailer.message import Attachment msg = Message( subject="testing", recipients=["*****@*****.**"], sender='sender', body="testing" ) attachment = Attachment( data=b"this is a test", content_type="text/plain" ) msg.attach(attachment) a = msg.attachments[0] self.assertTrue(a.filename is None) self.assertEqual(a.disposition, 'attachment') self.assertEqual(a.content_type, "text/plain") self.assertEqual(a.data, b"this is a test")
def test_to_message_multipart(self): from pyramid_mailer.message import Message, Attachment response = Message(recipients=['To'], sender='From', subject='Subject', body='Body', html='Html') attachment_type = 'text/html' this = os.path.abspath(__file__) attachment = Attachment(filename=this, content_type=attachment_type, data='data'.encode('ascii'), disposition='disposition') response.attach(attachment) message = response.to_message() self.assertEqual(message['Content-Type'], 'multipart/mixed') payload = message.get_payload() self.assertEqual(len(payload), 2) self.assertEqual(payload[0]['Content-Type'], 'multipart/alternative') self.assertTrue(payload[1]['Content-Type'].startswith(attachment_type)) alt_payload = payload[0].get_payload() self.assertTrue( alt_payload[0]['Content-Type'].startswith('text/plain')) self.assertTrue(alt_payload[1]['Content-Type'].startswith('text/html'))
def accountant_mail(appstruct): """ this function returns a message object for the mailer it consists of a mail body and an attachment attached to it """ unencrypted = make_mail_body(appstruct) #print("accountant_mail: mail body: \n%s") % unencrypted #print("accountant_mail: type of mail body: %s") % type(unencrypted) encrypted = encrypt_with_gnupg(unencrypted) #print("accountant_mail: mail body (enc'd): \n%s") % encrypted #print("accountant_mail: type of mail body (enc'd): %s") % type(encrypted) message = Message( subject="[C3S] Yes! a new member", sender="*****@*****.**", recipients=["*****@*****.**"], body=encrypted ) #print("accountant_mail: csv_payload: \n%s") % generate_csv(appstruct) #print( # "accountant_mail: type of csv_payload: \n%s" #) % type(generate_csv(appstruct)) csv_payload_encd = encrypt_with_gnupg(generate_csv(appstruct)) #print("accountant_mail: csv_payload_encd: \n%s") % csv_payload_encd #print( # "accountant_mail: type of csv_payload_encd: \n%s" #) % type(csv_payload_encd) attachment = Attachment( "C3S-SCE-AFM.csv.gpg", "application/gpg-encryption", csv_payload_encd) message.attach(attachment) return message
def mailer_send(subject="!", sender=None, recipients=[], body=None, html=None, attachments=[]): try: request = get_current_request() if sender is None: sender = request.registry.settings['lac.admin_email'] mailer = get_mailer(request) message = Message(subject=subject, sender=sender, recipients=recipients, body=body, html=html) for attachment in attachments: attachment = Attachment(attachment.title, attachment.mimetype, attachment) message.attach(attachment) if transaction.get().status == Status.COMMITTED: mailer.send_immediately(message) else: mailer.send(message) except Exception: pass
def test_to_message_multipart_with_b64encoding(self): from pyramid_mailer.message import Message, Attachment response = Message(recipients=['To'], sender='From', subject='Subject', body='Body', html='Html') this = os.path.abspath(__file__) with open(this, 'rb') as data: attachment = Attachment( filename=this, content_type='application/octet-stream', disposition='disposition', transfer_encoding='base64', data=data, ) response.attach(attachment) message = response.to_message() payload = message.get_payload()[1] self.assertEqual(payload.get('Content-Transfer-Encoding'), 'base64') self.assertEqual( payload.get_payload(), _bencode(self._read_filedata(this, 'rb')).decode('ascii'))
def accountant_mail(appstruct): """ this function returns a message object for the mailer it consists of a mail body and an attachment attached to it """ unencrypted = make_mail_body(appstruct) #print("accountant_mail: mail body: \n%s") % unencrypted #print("accountant_mail: type of mail body: %s") % type(unencrypted) encrypted = encrypt_with_gnupg(unencrypted) #print("accountant_mail: mail body (enc'd): \n%s") % encrypted #print("accountant_mail: type of mail body (enc'd): %s") % type(encrypted) message_recipient = appstruct['message_recipient'] message = Message(subject="[C3S] Yes! a new member", sender="*****@*****.**", recipients=[message_recipient], body=encrypted) #print("accountant_mail: csv_payload: \n%s") % generate_csv(appstruct) #print( # "accountant_mail: type of csv_payload: \n%s" #) % type(generate_csv(appstruct)) csv_payload_encd = encrypt_with_gnupg(generate_csv(appstruct)) #print("accountant_mail: csv_payload_encd: \n%s") % csv_payload_encd #print( # "accountant_mail: type of csv_payload_encd: \n%s" #) % type(csv_payload_encd) attachment = Attachment("C3S-SCE-AFM.csv.gpg", "application/gpg-encryption", csv_payload_encd) message.attach(attachment) return message
def test_to_message_multipart_with_qpencoding(self): from pyramid_mailer.message import Message, Attachment response = Message( recipients=['To'], sender='From', subject='Subject', body='Body', html='Html' ) this = os.path.abspath(__file__) with open(this, 'rb') as data: attachment = Attachment( filename=this, content_type='application/octet-stream', disposition='disposition', transfer_encoding='quoted-printable', data=data, ) response.attach(attachment) message = response.to_message() payload = message.get_payload()[1] self.assertEqual( payload.get('Content-Transfer-Encoding'), 'quoted-printable' ) self.assertEqual( payload.get_payload(), _qencode(self._read_filedata(this,'rb')).decode('ascii') )
def mailer_send(subject="!", sender=None, recipients=[], body=None, html=None, attachments=[]): try: request = get_current_request() if sender is None: sender = request.registry.settings['mail.default_sender'] mailer = get_mailer(request) message = Message(subject=subject, sender=sender, recipients=recipients, body=body, html=html) for attachment in attachments: attachment = Attachment(attachment.title, attachment.mimetype, attachment) message.attach(attachment) if transaction.get().status == Status.COMMITTED: mailer.send_immediately(message) else: mailer.send(message) except Exception: pass
def test_to_message_with_html_attachment(self): from pyramid_mailer.message import Message, Attachment response = Message(recipients=["To"], sender="From", subject="Subject", body="Body") attachment = Attachment(data=b"data", content_type="text/html") response.attach(attachment) message = response.to_message() att_payload = message.get_payload()[1] self.assertEqual(att_payload["Content-Type"], 'text/html; charset="us-ascii"') self.assertEqual(att_payload.get_payload(), _bencode(b"data").decode("ascii"))
def test_to_message_with_binary_attachment(self): from pyramid_mailer.message import Message, Attachment response = Message(recipients=["To"], sender="From", subject="Subject", body="Body") data = os.urandom(100) attachment = Attachment(data=data, content_type="application/octet-stream") response.attach(attachment) message = response.to_message() att_payload = message.get_payload()[1] self.assertEqual(att_payload["Content-Type"], "application/octet-stream") self.assertEqual(att_payload.get_payload(), _bencode(data).decode("ascii"))
def accountant_mail(appstruct): unencrypted = u""" Yay! we got a declaration of intent through the form: \n firstname: \t\t %s lastname: \t\t %s email: \t\t %s street & no: \t\t %s address2: \t\t %s postcode: \t\t %s city: \t\t %s country: \t\t %s activities: \t\t %s created3: \t\t $s member of collecting society: %s understood declaration text: %s consider joining \t %s noticed data protection: \t %s that's it.. bye!""" % ( unicode(appstruct['firstname']), unicode(appstruct['lastname']), unicode(appstruct['email']), unicode(appstruct['address1']), unicode(appstruct['address2']), unicode(appstruct['postCode']), unicode(appstruct['city']), unicode(appstruct['country']), unicode(appstruct['at_least_three_works']), unicode(appstruct['member_of_colsoc']), unicode(appstruct['understood_declaration']), unicode(appstruct['consider_joining']), unicode(appstruct['noticed_dataProtection']), ) message = Message( subject="[c3s] Yes! a new letter of intent", sender="*****@*****.**", recipients=["*****@*****.**"], body=str(encrypt_with_gnupg((unencrypted))) ) attachment = Attachment("foo.gpg", "application/gpg-encryption", unicode(encrypt_with_gnupg(u"foo to the bar!"))) # TODO: make attachment contents a .csv with the data supplied. message.attach(attachment) return message
def mail_submission(context, request, appstruct): mailer = get_mailer(request) message = Message(subject=appstruct['subject'], sender=appstruct['name'] + ' <' + appstruct['sender'] + '>', extra_headers={'X-Mailer': "kotti_contactform"}, recipients=[context.recipient], body=appstruct['content']) if 'attachment' in appstruct and appstruct['attachment'] is not None: message.attach(Attachment( filename=appstruct['attachment']['filename'], content_type=appstruct['attachment']['mimetype'], data=appstruct['attachment']['fp'] )) mailer.send(message)
def mail_submission(context, request, appstruct): mailer = get_mailer(request) message = Message(subject=appstruct['subject'], sender=appstruct['name'] + ' <' + appstruct['sender'] + '>', extra_headers={'X-Mailer': "kotti_contactform"}, recipients=[context.recipient], body=appstruct['content']) if 'attachment' in appstruct and appstruct['attachment'] is not None: message.attach( Attachment(filename=appstruct['attachment']['filename'], content_type=appstruct['attachment']['mimetype'], data=appstruct['attachment']['fp'])) mailer.send(message)
def accountant_mail(appstruct): unencrypted = make_mail_body(appstruct) message = Message(subject="[c3s] Yes! a new letter of intent", sender="*****@*****.**", recipients=["*****@*****.**"], body=unicode(encrypt_with_gnupg((unencrypted)))) attachment = Attachment("foo.gpg", "application/gpg-encryption", unicode(encrypt_with_gnupg(u"foo to the bar!"))) # TODO: make attachment contents a .csv with the data supplied. message.attach(attachment) return message
def test_to_message_with_html_attachment(self): from pyramid_mailer.message import Message, Attachment response = Message( recipients=['To'], sender='From', subject='Subject', body='Body', ) attachment = Attachment(data=b'data', content_type='text/html') response.attach(attachment) message = response.to_message() att_payload = message.get_payload()[1] self.assertEqual(att_payload['Content-Type'], 'text/html; charset="us-ascii"') self.assertEqual(att_payload.get_payload(), _bencode(b'data').decode('ascii'))
def accountant_mail(appstruct): unencrypted = make_mail_body(appstruct) message = Message( subject="[c3s] Yes! a new letter of intent", sender="*****@*****.**", recipients=["*****@*****.**"], body=unicode(encrypt_with_gnupg((unencrypted))) ) attachment = Attachment("foo.gpg", "application/gpg-encryption", unicode(encrypt_with_gnupg(u"foo to the bar!"))) # TODO: make attachment contents a .csv with the data supplied. message.attach(attachment) return message
def test_send(self): from pyramid_mailer.mailer import Mailer from pyramid_mailer.message import Attachment from pyramid_mailer.message import Message mailer = Mailer() msg = Message(subject="testing", sender="*****@*****.**", recipients=["*****@*****.**"], body="test") msg.attach(Attachment('test.txt', data=b"this is a test", content_type="text/plain")) mailer.send(msg)
def test_to_message_multipart_with_qpencoding(self): from pyramid_mailer.message import Message, Attachment response = Message(recipients=["To"], sender="From", subject="Subject", body="Body", html="Html") this = os.path.abspath(__file__) data = open(this, "rb") attachment = Attachment( filename=this, content_type="application/octet-stream", disposition="disposition", transfer_encoding="quoted-printable", data=data, ) response.attach(attachment) message = response.to_message() payload = message.get_payload()[1] self.assertEqual(payload.get("Content-Transfer-Encoding"), "quoted-printable") self.assertEqual(payload.get_payload(), _qencode(self._read_filedata(this, "rb")).decode("ascii"))
def mail_submission(context, request, appstruct): mailer = get_mailer(request) message = Message( subject=appstruct["subject"], sender="{name} <{email}>".format(name=appstruct["name"], email=context.sender), extra_headers={"X-Mailer": "kotti_contactform", "Reply-To": "{name} <{sender}>".format(**appstruct)}, recipients=[context.recipient], body=appstruct["content"], ) if "attachment" in appstruct and appstruct["attachment"] is not None: message.attach( Attachment( filename=appstruct["attachment"]["filename"], content_type=appstruct["attachment"]["mimetype"], data=appstruct["attachment"]["fp"], ) ) mailer.send(message)
def test_attach(self): from pyramid_mailer.message import Message from pyramid_mailer.message import Attachment msg = Message(subject="testing", recipients=["*****@*****.**"], body="testing") msg.attach(Attachment(data="this is a test", content_type="text/plain")) a = msg.attachments[0] self.assertTrue(a.filename is None) self.assertEqual(a.disposition, "attachment") self.assertEqual(a.content_type, "text/plain") self.assertEqual(a.data, "this is a test") response = msg.get_response() self.assertEqual(len(response.attachments), 1)
def test_to_message_with_binary_attachment(self): from pyramid_mailer.message import Message, Attachment response = Message( recipients=['To'], sender='From', subject='Subject', body='Body', ) data = os.urandom(100) attachment = Attachment( data=data, content_type='application/octet-stream', ) response.attach(attachment) message = response.to_message() att_payload = message.get_payload()[1] self.assertEqual(att_payload['Content-Type'], 'application/octet-stream') self.assertEqual(att_payload.get_payload(), _bencode(data).decode('ascii'))
def mail_submission(context, request, appstruct): mailer = get_mailer(request) message = Message( subject=appstruct['subject'], sender='{name} <{email}>'.format( name=appstruct['name'], email=context.sender), extra_headers={ 'X-Mailer': "kotti_contactform", 'Reply-To': '{name} <{sender}>'.format(**appstruct), }, recipients=[context.recipient], body=appstruct['content']) if 'attachment' in appstruct and appstruct['attachment'] is not None: message.attach(Attachment( filename=appstruct['attachment']['filename'], content_type=appstruct['attachment']['mimetype'], data=appstruct['attachment']['fp'] )) mailer.send(message)
def send_mail(event): """ send a mail to dests with subject and body beeing set :param @event: an event object providing : The following methods : is_key_event : return True or False get_attachment : return an attachment object or None The following attributes: request : access to the current request object sendermail: the mail's sender recipients : list of recipients (a string) subject : the mail's subject body : the body of the mail settings : the app settings """ if event.is_key_event(): recipients = event.recipients if recipients: log.info(u"Sending an email to '{0}'".format(recipients)) headers, mail_body = _handle_optout(event.settings, event.body) try: mailer = get_mailer(event.request) message = Message( subject=event.subject, sender=event.sendermail, recipients=recipients, body=mail_body, extra_headers=headers, ) attachment = event.get_attachment() if attachment: message.attach(attachment) mailer.send_immediately(message) except: log.exception( u" - An error has occured while sending the \ email(s)" )
def test_to_message_multipart(self): from pyramid_mailer.message import Message, Attachment response = Message(recipients=["To"], sender="From", subject="Subject", body="Body", html="Html") attachment_type = "text/html" this = os.path.abspath(__file__) attachment = Attachment( filename=this, content_type=attachment_type, data="data".encode("ascii"), disposition="disposition" ) response.attach(attachment) message = response.to_message() self.assertEqual(message["Content-Type"], "multipart/mixed") payload = message.get_payload() self.assertEqual(len(payload), 2) self.assertEqual(payload[0]["Content-Type"], "multipart/alternative") self.assertTrue(payload[1]["Content-Type"].startswith(attachment_type)) alt_payload = payload[0].get_payload() self.assertTrue(alt_payload[0]["Content-Type"].startswith("text/plain")) self.assertTrue(alt_payload[1]["Content-Type"].startswith("text/html"))
def send_mail(request): mailer = Mailer( host='smtp.gmail.com', port=587, #??? username='******', password='******', tls=True) if request.params.get('email') is not None: email = request.params['email'] else: email = "the email does not exist" send_topic = 'Welcome to join us for the seminar' send_er = '*****@*****.**' send_to = [email] send_this = "Thank you for signing up at our website..." message = Message( subject = send_topic, sender = send_er, recipients = send_to, body = send_this ) here = os.path.dirname(__file__) att1 = os.path.join(here, 'static','velur1.pdf') attachment = Attachment(att1, "image/jpg", open(att1, "rb")) message.attach(attachment) here = os.path.dirname(__file__) att2 = os.path.join(here, 'static','velur2.pdf') attachment = Attachment(att2, "image/jpg", open(att2, "rb")) message.attach(attachment) # mailer.send_immediately(message, fail_silently=False) mailer.send(message) return Response(email)
def create_accountant_mail(member, sender, recipients): """ Create an email message information the accountant about the new membership application. """ unencrypted = make_mail_body(member) encrypted = encrypt_with_gnupg(unencrypted) message = Message( subject="[C3S] Yes! a new member", sender=sender, recipients=recipients, body=encrypted ) csv_payload_encd = encrypt_with_gnupg(generate_csv(member)) attachment = Attachment( "C3S-SCE-AFM.csv.gpg", "application/gpg-encryption", csv_payload_encd) message.attach(attachment) return message
def test_attach(self): from pyramid_mailer.message import Message from pyramid_mailer.message import Attachment msg = Message(subject="testing", recipients=["*****@*****.**"], body="testing") msg.attach(Attachment(data="this is a test", content_type="text/plain")) a = msg.attachments[0] self.assert_(a.filename is None) self.assert_(a.disposition == 'attachment') self.assert_(a.content_type == "text/plain") self.assert_(a.data == "this is a test") response = msg.get_response() self.assert_(len(response.attachments) == 1)
def test_to_message_multipart(self): from pyramid_mailer.message import Message, Attachment response = Message( recipients=['To'], sender='From', subject='Subject', body='Body', html='Html' ) attachment_type = 'text/html' this = os.path.abspath(__file__) attachment = Attachment( filename=this, content_type=attachment_type, data='data'.encode('ascii'), disposition='disposition' ) response.attach(attachment) message = response.to_message() self.assertEqual(message['Content-Type'], 'multipart/mixed') payload = message.get_payload() self.assertEqual(len(payload), 2) self.assertEqual( payload[0]['Content-Type'], 'multipart/alternative' ) self.assertTrue( payload[1]['Content-Type'].startswith(attachment_type) ) alt_payload = payload[0].get_payload() self.assertTrue( alt_payload[0]['Content-Type'].startswith('text/plain') ) self.assertTrue( alt_payload[1]['Content-Type'].startswith('text/html') )
def send_mail(request, recipients, body, subject, attachment=None): """ Try to send an email with the given datas :param obj request: a pyramid request object :param list recipients: A list of recipients strings :param str body: The body of the email :param str subject: The subject of the email :param obj attachment: A pyramid_mailer.message.Attachment object """ if not hasattr(recipients, '__iter__'): recipients = [recipients] if len(recipients) == 0: return False logger.info(u"Sending an email to '{0}'".format(recipients)) settings = request.registry.settings headers, mail_body = _handle_optout(settings, body) try: recipients = [format_mail(recipient) for recipient in recipients] sender = get_sender(settings) mailer = get_mailer(request) message = Message(subject=subject, sender=sender, recipients=recipients, body=mail_body, extra_headers=headers) if attachment: message.attach(attachment) mailer.send_immediately(message) except Exception: import traceback traceback.print_exc() logger.exception(u" - An error has occured while sending the \ email(s)") return False return True
def test_to_message_with_html_attachment(self): from pyramid_mailer.message import Message, Attachment response = Message( recipients=['To'], sender='From', subject='Subject', body='Body', ) attachment = Attachment( data=b'data', content_type='text/html' ) response.attach(attachment) message = response.to_message() att_payload = message.get_payload()[1] self.assertEqual( att_payload['Content-Type'], 'text/html; charset="us-ascii"' ) self.assertEqual( att_payload.get_payload(), _bencode(b'data').decode('ascii') )
def send_mail(request): mailer = Mailer( host='smtp.gmail.com', port=587, #??? username='******', password='******', tls=True) if request.params.get('email') is not None: email = request.params['email'] else: email = "the email does not exist" send_topic = 'Welcome to join us for the seminar' send_er = '*****@*****.**' send_to = [email] send_this = "Thank you for signing up at our website..." message = Message(subject=send_topic, sender=send_er, recipients=send_to, body=send_this) attachment = Attachment("velur1.pdf", "image/jpg", open("velur1.pdf", "rb")) message.attach(attachment) attachment = Attachment("velur2.pdf", "image/jpg", open("velur2.pdf", "rb")) message.attach(attachment) # mailer.send_immediately(message, fail_silently=False) mailer.send(message) return Response(email)
def send_mail(event): """ send a mail to dests with subject and body beeing set :param @event: an event object providing : The following methods : is_key_event : return True or False get_attachment : return an attachment object or None The following attributes: request : access to the current request object sendermail: the mail's sender recipients : list of recipients (a string) subject : the mail's subject body : the body of the mail settings : the app settings """ if event.is_key_event(): recipients = event.recipients if recipients: log.info(u"Sending an email to '{0}'".format(recipients)) headers, mail_body = _handle_optout(event.settings, event.body) try: mailer = get_mailer(event.request) message = Message(subject=event.subject, sender=event.sendermail, recipients=recipients, body=mail_body, extra_headers=headers) attachment = event.get_attachment() if attachment: message.attach(attachment) mailer.send_immediately(message) except: log.exception(u" - An error has occured while sending the \ email(s)")
def send_mail(request): mailer = Mailer( host='smtp.gmail.com', port=587, #??? username='******', password='******', tls=True) if request.params.get('email') is not None: email = request.params['email'] else: email = "the email does not exist" send_topic = 'Welcome to join us for the seminar' send_er = '*****@*****.**' send_to = [email] send_this = "Thank you for signing up at our website..." message = Message( subject = send_topic, sender = send_er, recipients = send_to, body = send_this ) attachment = Attachment("velur1.pdf", "image/jpg", open("velur1.pdf", "rb")) message.attach(attachment) attachment = Attachment("velur2.pdf", "image/jpg", open("velur2.pdf", "rb")) message.attach(attachment) # mailer.send_immediately(message, fail_silently=False) mailer.send(message) return Response(email)
def test_to_message_with_binary_attachment(self): from pyramid_mailer.message import Message, Attachment response = Message( recipients=['To'], sender='From', subject='Subject', body='Body', ) data = os.urandom(100) attachment = Attachment( data=data, content_type='application/octet-stream', ) response.attach(attachment) message = response.to_message() att_payload = message.get_payload()[1] self.assertEqual( att_payload['Content-Type'], 'application/octet-stream' ) self.assertEqual( att_payload.get_payload(), _bencode(data).decode('ascii') )