def changeoassword(request): if request.method == 'GET': return render(request, 'changepwd.html') elif request.method == 'POST': email = request.POST['email'] oldpassword = request.POST['oldpassword'] if str(request.POST['password1']) != str(request.POST['password2']): context = { 'error_message': "New Passwords are not same", 'email': request.POST['email'], 'oldpassword': request.POST['oldpassword'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'changepwd.html', context) try: user = User.objects.get(email__iexact=email) if str(user.password) != oldpassword: context = { 'error_message': "Password is not correct", 'email': request.POST['email'], 'oldpassword': request.POST['oldpassword'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'changepwd.html', context) user.password = str(request.POST['password1']) user.save() sg = sendgrid.SendGridAPIClient( apikey= "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" ) from_email = Email("*****@*****.**") subject = "TUCAN STUDIO UK - Changed your password" to_email = Email(email) content = Content("text/html", render_to_string('email_update_password.html')) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if 'account_id' in request.session: del request.session['account_id'] return HttpResponseRedirect( "https://supbotserver.herokuapp.com/api/signin/") except: context = { 'error_message': "Unable to find email", 'email': request.POST['email'], 'oldpassword': request.POST['oldpassword'], 'password1': request.POST['password1'], 'password2': request.POST['password2'] } return render(request, 'changepwd.html', context)
def send_mail(from_email, _to_email, subject, body, html=False, from_name="Gitcoin.co", cc_emails=None): # make sure this subscriber is saved to_email = _to_email get_or_save_email_subscriber(to_email, 'internal') # setup sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(from_email, from_name) to_email = Email(to_email) contenttype = "text/plain" if not html else "text/html" # build content content = Content(contenttype, html) if html else Content(contenttype, body) if settings.DEBUG: to_email = Email(settings.CONTACT_EMAIL) #just to be double secret sure of what were doing in dev subject = "[DEBUG] " + subject mail = Mail(from_email, subject, to_email, content) # build personalization (BCC + CC) p = Personalization() p.add_to(to_email) if cc_emails: #only add CCif not in prod for cc_addr in set(cc_emails): cc_addr = Email(cc_addr) if settings.DEBUG: cc_addr = to_email if cc_addr._email != to_email._email: p.add_to(cc_addr) p.add_bcc(Email(settings.BCC_EMAIL)) mail.add_personalization(p) # debug logs print("-- Sending Mail '{}' to {}".format(subject, _to_email)) # send mails response = sg.client.mail.send.post(request_body=mail.get()) return response
def sendgrid_deliver(self, title, body): """ Delivery email by Sendgrid. Arguments: title: mail title body: body text """ api_key = self.get_config('SENDGRID', 'apikey') from_email = Email(self.get_config('SMTP', 'from')) to_email = To(self.get_config('SMTP', 'to')) content = Content("text/html", body) mail = Mail(from_email, to_email, title, content) sendgrid_api = sendgrid.SendGridAPIClient(api_key=api_key) sendgrid_api.client.mail.send.post(request_body=mail.get())
def send_email(): """Send user account validation.""" sender = os.getenv('SENDER_EMAIL') notification_message = ('Hola. Hay un nuevo usuario en ROAp.') sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email(sender) to_email = Email(os.getenv('ROAP_ADMIN')) subject = "ROAp: Notificación de nuevo usuario" content = Content("text/html", notification_message) mail = Mail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=mail.get())
def lambda_handler(event, context): payload = event.get("data", {}) message = Mail( from_email=phone_to_email(payload.get('From')), to_emails='*****@*****.**', subject='Text message', plain_text_content= Content("text/plain", payload.get('Body')) ) response = sendgrid_api.send(message) return '<Response> {} </Response>'.format(response.body)
def send_emails(from_email, to_emails: list, subject, content, content_type='text/plain'): from_email = Email(from_email) subject = subject content = Content(content_type, content) mail = Mail(from_email, subject, None, content) personalization = get_mock_personalization_dict(to_emails) mail.add_personalization(build_personalization(personalization)) response = client.client.mail.send.post(request_body=mail.get()) if response.status_code > 299: raise Exception(response.body)
def email_send(email, to_email, subject, content): env = environ.Env() env.read_env() sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(email) to_email = Email(to_email) subject = subject content = Content("text/plain", content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return response.status_code
def send_email(title, url): from_email = Email("*****@*****.**") to_email = Email(recipient) date = datetime.now().strftime("%B %d %G") subject = "[Daily Corgo] {}".format(date) content = Content("text/html", format_content(title, url)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body)
def create_mail_config(from_email: str, subject: str, to_emails: List[str], content: str) -> dict: mail = Mail() mail.from_email = Email(from_email) mail.subject = subject personalization = Personalization() for email in to_emails: personalization.add_to(Email(email)) mail.add_personalization(personalization) mail.add_content(Content("text/html", content)) return mail.get()
def post(self, request, format=None): data = json.loads(request.body) name = data['name'] email = data['email'] tel = data['tel'] message = data['message'] staff_email = getEmails() subject = "Demande de contact" message_content = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Demande de contact 2</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat"> </head> <p style="font-family : Montserrat;font-size:130%%;"> CafeAum,<br> %s (email : %s / tel : %s) a laissé une demande de contact. Son message :<br> "%s" <br><br> Merci de lui répondre dans les meilleurs délais. <br> </p> </html> """%(name, email, tel, '<br>'.join(message.splitlines())) sg = sendgrid.SendGridAPIClient(apikey=getApiKey()) from_email = Email(staff_email.noreply()) to_email = Email(staff_email.contact()) content = Content("text/html", message_content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if (response.status_code >= 200) and (response.status_code < 300): return Response({ 'status': 'OK', 'message': 'Email sent' }, status=status.HTTP_200_OK) else: return Response({ 'status': 'KO', 'message': 'Error' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def send_mail(from_email, to_email, subject, body, html=False, bcc_gitcoin_core=True, from_name="Gitcoin.co"): if (bcc_gitcoin_core): prepend_str = "Sent to {}\n".format(to_email) _body = prepend_str + str(body) if html: _html = prepend_str + str(html) else: _html = False _to_email = '*****@*****.**' send_mail(from_email, _to_email, subject, _body, _html, bcc_gitcoin_core=False) print("-- Sending Mail '{}' to {}".format(subject, to_email)) sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email(from_email, from_name) to_email = Email(to_email) contenttype = "text/plain" if not html else "text/html" content = Content(contenttype, html) if html else Content( contenttype, body) if settings.DEBUG: to_email = Email( settings.CONTACT_EMAIL ) #just to be double secret sure of what were doing in dev subject = "[DEBUG] " + subject mail = Mail(from_email, subject, to_email, content) # mail.add_header({'bcc' : settings.BCC_EMAIL}) #TODO response = sg.client.mail.send.post(request_body=mail.get()) return response
def sendReceivedSubmission(email, assignment, link): from_email = Email("*****@*****.**") subject = "{} Received Submission".format(assignment) to_email = Email(email) content = Content("text/html", "Good Luck!") mail = Mail(from_email, subject, to_email, content) user = User.query.filter_by(email=email).first() mail.personalizations[0].add_substitution(Substitution("-name-", user.firstname)) mail.personalizations[0].add_substitution(Substitution("-assignmentLink-", link)) mail.template_id = "89c4a861-283c-4ec5-8cef-3a3198e31b95" response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers)
def send_sd_email(name, fromemail, toemail, subject, email_content): print(name, fromemail, toemail, subject, email_content) sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = Email(fromemail) to_email = Email(toemail) content = Content(email_content['type'], email_content['content']) mail = Mail(from_email, subject, to_email, content) # mail.personalizations[0].add_substitution(Substitution("-name-", name)) try: response = sg.client.mail.send.post(request_body=mail.get()) except urllib.HTTPError as e: print(e.read()) exit() return response.status_code
def send_email(replyto_email, to_emails, content): """ Submits send_email jobs to SendGrid API """ from_email = Email("*****@*****.**") to_emails = To("*****@*****.**") subject = "Website message from: " + replyto_email content = Content("text/plain", content) message = Mail(from_email, to_emails, subject, content) message.reply_to = replyto_email try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) except Exception as e: return render_template('50x.html')
def send_email(to_email, certificateLink): from_email = Email(app.config.get('FROM_EMAIL')) to_email = Email(to_email) content = Content('text/html', ' ') mail = Mail(from_email, ' ', to_email, content) mail.personalizations[0].add_substitution( Substitution("-certificateLink-", certificateLink) ) mail.template_id = app.config.get('SENDGRID_TEMPLATE_ID') try: sendgrid.client.mail.send.post(request_body=mail.get()) except Exception: pass
def send_email(sendgrid_api_key, email_to, email_str): sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key) from_email = Email("no_reply@flask_static_comments.com") to_email = Email(email_to) subject = "A comment was submitted on your blog" content = Content("text/html", email_str) mail = Mail(from_email, subject, to_email, content) try: response = sg.client.mail.send.post(request_body=mail.get()) except sg_exceptions.HTTPError as e: app.logger.info("Error encountered when sending email: {}".format(e.body)) return False return True
def notify(note, email_address): # Say 'someone' if the byline is empty. who = note.byline or 'someone' subject = 'saythanks.io: {} sent a note!'.format(who) message = TEMPLATE.format(note.body, note.byline) from_address = Email('*****@*****.**', name="SayThanks.io") to_address = Email(email_address) content = Content('text/plain', message) mail = Mail(from_address, subject, to_address, content) response = sg.client.mail.send.post(request_body=mail.get())
def send_email(filename, email): ''' THIRD CELERY TASK ''' link = "<a href='{}{}'>{}</a>".format( settings.URL_HOST, settings.MEDIA_URL + filename, filename) sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = Email('youtube_convertor@gmail') subject = filename to_email = Email(email) content = Content('text/html', link) mail = Mail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=mail.get())
def send_email(to_email, subject, html_body): """Send email to to_email, with subject and body.""" logger.info({ 'msg': 'sending email', 'to_email': to_email, 'subject': subject }) mail = Mail(Email(FROM_EMAIL), subject, Email(to_email), Content("text/plain", html_body)) response = sg.client.mail.send.post(request_body=mail.get()) logger.info('sent email', to_email=to_email, subject=subject)
def post(self, request, format=None): data = json.loads(request.body) email = data['email'] token = data['token'] staff_email = getEmails() subject = "Renouvellement de mot de passe" message_content = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Renouvellement de mot de passe</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat"> </head> <p style="font-family : Montserrat;font-size:130%%;"> Bonjour,<br> Pour mettre à jour votre mot de passe, veuillez cliquer sur le lien suivant : <br> <a href="http://cafeaum.com/recovery/%s">http://cafeaum.com/recovery/%s</a><br> Attention ce lien n'est valide que pour 24h, aussi nous vous recommandons de modifier votre mot de passe dès que possible.<br><br> L'équipe CafeAum <br> </p> </html> """%(token,token) sg = sendgrid.SendGridAPIClient(apikey=getApiKey()) from_email = Email(staff_email.noreply()) to_email = Email(email) content = Content("text/html", message_content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if (response.status_code >= 200) and (response.status_code < 300): return Response({ 'status': 'OK', 'message': 'Email sent' }, status=status.HTTP_200_OK) else: return Response({ 'status': 'KO', 'message': 'Error' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def build(self, to_email, subject, body): mail = Mail() from_email = self.config['MAILER_FROM_EMAIL'] from_name = self.config['MAILER_FROM_NAME'] mail.from_email = Email(from_email, from_name) mail.subject = subject personalization = Personalization() personalization.add_to(Email(to_email)) mail.add_personalization(personalization) mail.add_content(Content("text/plain", body)) return mail.get()
def send_confirm_email(to_email, account_id): try: sender = Email(os.environ.get('EMAIL_USERNAME')) recipient = To(to_email) subject = "Please confirm your email" content = Content("text/html", "Click <a href=\"http://127.0.0.1/confirm/%s\">here</a> to confirm your email." % account_id) mail = Mail(sender, recipient, subject, content) mail_json = mail.get() response = sg.client.mail.send.post(request_body=mail_json) print(response.status_code) print(response.headers) except HTTPError as e: print(e.to_dict)
def send_email(email_from, email_to, subject, message): sendclnt = SendGridAPIClient(apikey=config.sendgrid_api_key) fr_email = Email(email_from) to_email = Email(email_to) content = Content("text/plain", message) mail = Mail(fr_email, subject, to_email, content) response = sendclnt.client.mail.send.post(request_body=mail.get()) # print(response.status_code) # print(response.body) # print(response.headers) return response
def send_email(from_email, to_email, subject, content, content_type='text/plain'): from_email = Email(from_email) to_email = Email(to_email) subject = subject content = Content(content_type, content) mail = Mail(from_email, subject, to_email, content) response = client.client.mail.send.post(request_body=mail.get()) if response.status_code > 299: raise Exception(response.body)
def sendgridmail(user,TEXT): sg = sendgrid.SendGridAPIClient('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') from_email = Email("*****@*****.**") # Change to your verified sender to_email = To(user) # Change to your recipient subject = "Sending with SendGrid is Fun" content = Content("text/plain",TEXT) mail = Mail(from_email, to_email, subject, content) # Get a JSON-ready representation of the Mail object mail_json = mail.get() # Send an HTTP POST request to /mail/send response = sg.client.mail.send.post(request_body=mail_json) print(response.status_code) print(response.headers)
def send(self): response = None # https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail/mail_example.py mail = Mail() mail.from_email = EmailAddr(self.from_email) mail.subject = self.subject personalization = Personalization() personalization.add_to(EmailAddr(self.to_email)) mail.add_personalization(personalization) mail.add_content(Content("text/plain", self.body_text)) body_html = self.body_html if body_html: mail.add_content(Content("text/html", self.body_html)) # on success it returns 202 # https://sendgrid.com/docs/API_Reference/api_v3.html response = self.interface.client.mail.send.post(request_body=mail.get()) if response.status_code >= 400: raise SendError(response) return response
def _send_email(subject, to, html_body): """ :param subject: 邮件主题 :param to: 收件人邮箱地址 :param html_body :邮件主体部分 :return :``response`` """ sg = SendGridAPIClient(apikey=current_app.config["SENDGRID_API_KEY"]) from_email = Email(current_app.config["EMAIL_SENDER"]) to_email = Email(to) html_content = Content("text/html", html_body) mail = Mail(from_email, subject, to_email, content=html_content) response = sg.client.mail.send.post(request_body=mail.get()) return response
def send_email( email_to, message, subject, attachment=None, filetype="application/pdf", request=None, filename=None, ): """given an email, a message, and an attachment, and a SendGrid API key is defined in settings, send an attachment to the user. We return a message to print to the interface. Parameters ========== email_to: the email to send the message to message: the html content for the body subject: the email subject attachment: the attachment file on the server """ if not SENDGRID_API_KEY or not SENDGRID_SENDER_EMAIL: if request is not None: messages.warning( request, "SendGrid secrets were not found in the environment. Please see https://vsoch.github.io/gcpdjango/docs/getting-started/#sendgrid-secrets", ) return False mail = Mail( Email(SENDGRID_SENDER_EMAIL), To(email_to), subject, Content("text/plain", message), ) # If the user has provided an attachment, add it if attachment: message.attachment = generate_attachment(filepath=attachment, filetype=filetype, filename=filename) try: sg = SendGridAPIClient(api_key=SENDGRID_API_KEY) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.headers) return True except Exception as e: print(e.message) return False
def _make_sendgrid_mail(self, message): mail = Mail() if message.sender: mail.from_email = Email(message.sender) else: mail.from_email = Email(self.default_sender) template_id = getattr(message, 'template_id', None) if template_id: mail.template_id = template_id if message.subject: mail.subject = message.subject if message.recipients: if type(message.recipients) == list: personalization = Personalization() for recipient in message.recipients: personalization.add_to(Email(recipient)) dynamic_template_data = getattr(message, 'dynamic_template_data', None) if dynamic_template_data: personalization.dynamic_template_data = dynamic_template_data mail.add_personalization(personalization) else: raise Exception("unsupported type yet") if message.body: mail.add_content(Content("text/plain", message.body)) if message.html: mail.add_content(Content("text/html", message.html)) if message.reply_to: mail.reply_to = Email(message.reply_to) return mail
def send(self, sender, subject, message, recipients=None, message_type="text/plain", api_key=None, attachments=None): """ @param sender:string (the sender of the email) @param recipient:list (list of recipients of the email) @param subject:string (subject of the email) @param message:string (content of the email) @param message_type:string (mime type of the email content) @param api_key:string (the api key of sendgrid) @param attachments:list (list of Attachment tuple) """ api_key = api_key or os.environ.get("SENDGRID_API_KEY", None) if recipients is None or recipients == []: return if attachments is None: attachments = [] if api_key is None: raise RuntimeError( "Make sure to export SENDGRID_API_KEY or pass your api key") sg = sendgrid.SendGridAPIClient(apikey=api_key) from_email = Email(sender) to_email = Email(recipients[0]) content = Content(message_type, message) mail = Mail(from_email, subject, to_email, content) to = list(set(recipients)) # no duplicates. if len(to) > 1: for receiver in to[1:]: mail.personalizations[0].add_to(Email(receiver)) for attachment in attachments: mail.add_attachment(self.build_attachment(attachment)) try: response = sg.client.mail.send.post(request_body=mail.get()) except Exception as e: self._log_info(e) raise e self._log_info("Email sent..") return response.status_code, response.body