def send_email(request): print(" u mejleru , data,", request.data) message = Mail( from_email=request.user_meta['email'], to_emails=request.data['email'] ) try: if request.data['data']['type'] == 'team': message.dynamic_template_data = { 'subject': 'Invitation to team', 'text': 'You have been invited to join team %s.' % (request.data['data']['team']), 'url': 'http://localhost:3000/register/' + request.data['token'] } if request.data['data']['type'] == 'project': message.dynamic_template_data = { 'subject': 'Invitation to project', 'text': F'You have been invited to join a project %s.' % (request.data['data']['project_name']), 'url': 'http://localhost:3000/register/' + request.data['token'] } except: message.dynamic_template_data = { 'subject': 'Invitation to project', 'text': F'You have been invited to join Kroon', 'url': 'http://localhost:3000/register/' + request.data['token'] } message.template_id = 'd-6356bd9d31b740d08ea7c633d04f874d' try: sg = SendGridAPIClient(os.environ['SENDGRID_API_KEY']) response = sg.send(message) except Exception as e: print("ERROR: ", e)
def send_mail(self, template_prefix, email, context): if context.get('activate_url'): account_confirm_email = 'accounts/confirm-email/' # prod context['activate_url'] = (str(context.get('current_site')) + account_confirm_email + context['key']) # local dev # context['activate_url'] = ( # str("http://127.0.0.1:8000/") + account_confirm_email + context['key'] # ) user = context.get('user') sg = SendGridAPIClient(settings.SENDGRID_API_KEY) message = Mail( from_email="*****@*****.**", subject='Activación de la cuenta', to_emails=f"{user.email}", ) message.dynamic_template_data = { "activate_url": f"{context.get('activate_url')}", "user": f"{context.get('user')}", "Sender_Name": "Adra Torrejon de ardoz", "Sender_Address": "calle primavera 15", "Sender_City": "Torrejon de ardoz", "Sender_State": "Madrid", "Sender_Zip": "28850" } message.template_id = 'd-8dddee085b5e4479a28b7dace0adf686' sg.send(message) elif context.get('password_reset_url'): user = context.get('user') sg = SendGridAPIClient(settings.SENDGRID_API_KEY) message = Mail( from_email="*****@*****.**", subject='Cambio de contraseña', to_emails=f"{user.email}", ) message.dynamic_template_data = { "url_cambiar": f"{context.get('password_reset_url')}", "user": f"{user}", "Sender_Name": "Adra Torrejon de ardoz", "Sender_Address": "calle primavera 15", "Sender_City": "Torrejon de ardoz", "Sender_State": "Madrid", "Sender_Zip": "28850" } message.template_id = 'd-ab0adafe4dd14cb4b9aba688b7200830' sg.send(message)
def contact(request): data = request.data userMail = data['pEmail'] msg = data['pMsg'] name = data['pName'] if userMail == '' or userMail == None or msg == '' or msg == None or name == '' or name == None or re.search( '[0-9!@#$%^&*<>/?":;]', name): return Response({'msg': 'false'}) if re.search('\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?', userMail): # to us TEMPLATE_ID = 'd-dd7f766ae8b54b3386b3acde943571a7' FROM_ID = '*****@*****.**' message = Mail(from_email=FROM_ID, to_emails='*****@*****.**') message.dynamic_template_data = { "name": name, "email": userMail, "message": msg } # print('name:{0},email:{1},msg:{2}'.format(name,userMail,msg),) message.template_id = TEMPLATE_ID try: send = SendGridAPIClient( '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' ) response = send.send(message) except Exception as e: print(e) return Response({'msg': 'false'}) # to the user TEMPLATE_ID = 'd-ad0a2cedc0bc41afbbadcafc9cfdb376' FROM_ID = '*****@*****.**' message = Mail(from_email=FROM_ID, to_emails=userMail) message.dynamic_template_data = {"name": name} message.template_id = TEMPLATE_ID try: send = SendGridAPIClient( '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' ) response = send.send(message) return Response({'msg': 'true'}) except Exception as e: print(e) return Response({'msg': 'false'}) else: return Response({'msg': 'false'})
def send_mail(self, template_prefix, email, context): dels = DelegacionData.objects.all().first() hostname_without_port = remove_www(self.request.get_host().split(':')[0]) if context.get('activate_url'): account_confirm_email = 'accounts/confirm-email/' context['activate_url'] = ( "http://" + str(hostname_without_port) + "/" + account_confirm_email + context['key']) user = context.get('user') sg = SendGridAPIClient(settings.SENDGRID_API_KEY) message = Mail( from_email=f"*****@*****.**", to_emails=f"{user.email}", ) message.dynamic_template_data = { "activate_url": f"{context.get('activate_url')}", "user": f"{context.get('user')}", "Sender_Name": f"{dels.nombre}", "Sender_Address": f"{dels.direccion}", "Sender_City": f"{dels.ciudad}", "Sender_State": f"{dels.provincia}", "Sender_Zip": f"{dels.codigo_postal}" } message.template_id = 'd-8dddee085b5e4479a28b7dace0adf686' response = sg.send(message) elif context.get('password_reset_url'): user = context.get('user') sg = SendGridAPIClient(settings.SENDGRID_API_KEY) message = Mail( from_email=f"*****@*****.**", to_emails=f"{user.email}", ) message.dynamic_template_data = { "url_cambiar": f"{context.get('password_reset_url')}", "user": f"{user}", "Sender_Name": f"{dels.nombre}", "Sender_Address": f"{dels.direccion}", "Sender_City": f"{dels.ciudad}", "Sender_State": f"{dels.provincia}", "Sender_Zip": f"{dels.codigo_postal}" } message.template_id = 'd-ab0adafe4dd14cb4b9aba688b7200830' response = sg.send(message)
def sendMail(tipo, destino, data): """ tipo: PWD= link to reset a password | REG= Código de registro destino = dirección(es) de email (1 string, +1 list) data = Dictionary JSON, name, last_name, code """ message = Mail( from_email='*****@*****.**', to_emails=destino #subject = 'Registro RappiLending' if (tipo == 'REG') else 'Restaurar contraseña' ) print(data) message.dynamic_template_data = { 'name': data.get('name'), 'last_name': data.get('last_name'), 'code': data.get('code') } message.template_id = 'd-d8285dc4e2a1417890ad340d2575d687' try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) # print(response.body) # print(response.headers) except Exception as error: print(error)
def send_mail(data: dict): """ {"country":"Bangladesh","cases":13770,"todayCases":636,"deaths":214,"todayDeaths":8,"recovered":2414,"active":11142, "critical":1,"casesPerOneMillion":84,"deathsPerOneMillion":1,"totalTests":116919,"testsPerOneMillion":710} :param data: :return: """ try: dynamic = { "total_cases": data.get("cases", 0), "total_deaths": data.get("deaths", 0), "total_recovered": data.get("recovered", 0), "today_deaths": data.get("todayDeaths", 0), "affected": data.get("todayCases", 0) } for mail in MAIL_LIST: message = Mail( from_email='*****@*****.**', to_emails=mail, ) message.template_id = TEMPLATE_ID message.dynamic_template_data = dynamic res = sg.send(message) print(res.status_code) except Exception as e: print(e)
def send_email(self, message, dynamic_template=False): """ Send messages via the sendgrid api""" email = Mail( from_email=message.from_email or self.conn_info["DEFAULT_FROM_EMAIL"], to_emails=message.to, ) email.dynamic_template_data = message.data email.template_id = TemplateId(message.template_id) try: response = self.sg_client.send(email) if response.status_code != 202: logger.error( f"Error encountered while sending Email: {response.status_code}" ) logger.debug( f"Email pushed to SendGrid successfully: {message.mime_message}" ) except Exception as e: logger.error(f"Error encountered while sending Email: {e}") return True
def dataUpload(request): data = json.loads(request.POST['model']) print(data,'\n',request.FILES) if data['firstName'] == '' or data['lastName'] == '' or data['dob'] == '' or data['phone'] == '' or data['email'] == '' or data['condition'] == '' or request.FILES['image'] == '' or request.FILES['image'] == None: return Response({'msg':'false'}) TEMPLATE_ID = 'd-625263b291ea4daa81874ffab170a132' FROM_ID = '*****@*****.**' message = Mail( from_email = FROM_ID, to_emails = data['email'] ) message.dynamic_template_data = { "name" : data['firstName'] } message.template_id = TEMPLATE_ID try: send = SendGridAPIClient("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") response = send.send(message) except: return Response({'msg':'false'}) members(firstName=data['firstName'],lastName=data['lastName'],dob=data['dob'][:10],phone=data['phone'],email=data['email'],condition=data['condition'],organization=data['organization'],msg=data['msg'],idProof=request.FILES['image']).save() return Response({'msg':'true'})
def send_mail(from_mail, username, to_mails, event1, event2): message = Mail( from_email=from_mail, to_emails=to_mails ) message.dynamic_template_data = { 'name': username, 'title1' : event1.title, 'src1' : link(event1.urlsafe), 'loc1': event1.location, 'date1': event1.date.strftime('%d-%m-%Y %H:%M'), 'title2' : event2.title, 'src2' : link(event2.urlsafe), 'loc2': event2.location, 'date2': event2.date.strftime('%d-%m-%Y %H:%M') } print('before') message.template_id = 'd-6607926b2aba4f8fba984dccdaa9ece6' client = SendGridAPIClient(API_KEY) response = client.send(message) code = response.status_code print('after') was_successful = lambda ret_code: ret_code // 100 in (2, 3) if not was_successful(code): raise Exception("Couldn't send e-mail: {} {}".format(code, response.body))
def forgot_password(): body = json.loads(request.get_data()) user_email = body["email"] try: # check if user email exists in database User.query.filter(User.email == user_email).first_or_404() except Exception: return jsonify({"Error": "Invalid email address"}) password_reset_serializer = URLSafeTimedSerializer(SECRET_KEY) password_reset_url = ('http://localhost:3000/reset-password/' + password_reset_serializer.dumps( user_email, salt='password-reset-salt')) message = Mail(from_email=TEST_EMAIL1, to_emails=user_email, subject='Reset your password', html_content='Link to reset password') message.template_id = TemplateId("d-582022551b084a2ba6e05b439ec5d1ee") message.dynamic_template_data = {"password_reset_url": password_reset_url} try: sg = SendGridAPIClient(SENDGRID_API_KEY) sg.send(message) except Exception: return jsonify({"Error": "Failed to send reset password email"}) return jsonify({"Success": "Reset password email sent"})
def send_verify_email(): # noqa: E501 # TODO Finish implementing this """Send Verify Email Get the current user # noqa: E501 :rtype: object """ current_user = get_jwt_identity() user = User.query.filter_by(email_lower=current_user).one_or_none() if not user.email_verified: message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject='Verify Learn with Grok Email') message.template_id = 'd-a6801f5ee6d0458197d515c6bbefa290' message.dynamic_template_data = { 'verify_email_link': 'https://localhost:3000/verifyEmail' } try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) if not user.verify_email_link_sent: user.verify_email_link_sent = True db.session.add(user) db.session.commit() except Exception as e: print(e.message) user_schema = UserSchema() return user_schema.dump(user), 200
def register(request): email = request.POST.get("email") password = request.POST.get("password") name = request.POST.get("name") mobile = request.POST.get('mobile') user = User.objects.filter(email=email) if user.exists(): return JsonResponse({ "Message": "Email Id is Already Taken", "Error": True }) user = User.objects.create_user(email=email, password=password) if User: profile = Profile.objects.create(user=user, Name=name, phone=mobile) message = Mail( from_email=settings.EMAIL_HOST_USER, to_emails=email, ) message.template_id = 'd-222f7a5ffe9446409a43c7d0c16feb4b' link = 'http://127.0.0.1:8000/accounts/verification/' + user.key message.dynamic_template_data = { 'name': name, 'link': link, 'Email': user.email } SendGridAPIClient(settings.SENDGRID_KEY).send(message) return JsonResponse({ "Message": "Account has been created successfully Please Verify your Email Id", 'Success': True }) else: return JsonResponse( {"Message": "Something Went Wrong Please Try Again"})
def send_mail(user, video_id_list): dist = user.email if not dist: return video_list = [Stream.objects.get(video_id=x) for x in video_id_list] tz = timezone.pytz.timezone(user.timezone) msg = Mail( From(settings.MAIL_ADDR), To(dist) ) msg.dynamic_template_data = { "video_list": [{ "video_id": x.video_id, "title": x.title, "thumb_url": x.thumb, "channel_id": x.channel_id, "channel_name": x.channel.title, "channel_thumb_url": x.channel.thumb} for x in video_list], "subject": f"{(video_list[0].start_at - timezone.now()).seconds // 60}分後に生放送が開始されます", "start_at": video_list[0].start_at.astimezone(tz).strftime("%m{0}%d{1} %H:%M").format(*"月日"), "remain_time_min": (video_list[0].start_at - timezone.now()).total_seconds() // 60, # "image": "http://youtube.dplab.biz" + static("images/YoutubeLiveSchedulerHeader.jpg"), # "unsubscribe": f"http://giftify.dplab.biz{reverse('account:unsubscribe_page')}?email={dist}&c={_condition_id}" } msg.template_id = "d-fd0b728c820b424dbe63e4154b47cc4b" try: sg = sendgrid.SendGridAPIClient(settings.SENDGRID_API) response = sg.send(msg.get()) except Exception as e: logger.error(e) print(e) return None logger.debug(f"[NOTIFY] Sent a Mail to {user.email}") print(f"[NOTIFY] Sent a Mail to {user.email}") return dist
def send_contact_info(contact, template_id): """ send texas russell volunteers the info submitting in the contact form """ message = Mail( from_email='*****@*****.**', to_emails=trr_volunteers ) message.reply_to = contact.email.data message.dynamic_template_data = { 'name': contact.name.data, 'email': contact.email.data, 'phone': contact.phone.data, 'city': contact.city.data, 'state': contact.state.data, 'subject': contact.subject.data, 'content': contact.content.data } message.template_id = template_id try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) except Exception as e: print('could not send') print(e.message)
def send_admin_confirmation_email_to_providers(providers: object, admin: object ): with app.app_context(): for provider in providers: # which admin uuid is this for? we need a body element identify this accept_token = create_access_token( identity=provider.uuid, fresh=True, expires_delta=False) # why cant we just sent the email to the email list? # Because transactional templates dont support substitution for a single To() class message = Mail( from_email=Email('*****@*****.**'), to_emails=provider.email, subject='Icarus Admin Request', is_multiple=True) message.template_id = environ.get("ADMIN_CONFIRMATION_TO_PROVIDERS_TEMPLATE_ID") message.dynamic_template_data = { 'adminName': admin.name, 'adminEmail': admin.email, 'adminUUID': admin.uuid, 'providerName': provider.name, 'acceptToken': accept_token, } try: sg = SendGridAPIClient(environ.get('SENDGRID_API_KEY')) response = sg.send(message) except Exception as e: print(e)
def send_dynamic(): """Send a dynamic email to a list of email addresses :returns API response code :raises Exception e: raises an exception""" # create Mail object and populate message = Mail(from_email=FROM_EMAIL, to_emails=TO_EMAILS) # pass custom values for our HTML placeholders message.dynamic_template_data = { "subject": "SendGrid Development", "place": "New York City", "event": "Twilio Signal", } message.template_id = TEMPLATE_ID # create our sendgrid client object, pass it our key, then send and return our response objects try: sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) response = sg.send(message) code, body, headers = response.status_code, response.body, response.headers print(f"Response code: {code}") print(f"Response headers: {headers}") print(f"Response body: {body}") print("Dynamic Messages Sent!") except Exception as e: print("Error: {0}".format(e)) return str(response.status_code)
def send_verification_email(firstname, email, verification_code): message = Mail(from_email='*****@*****.**', to_emails=email) email_data = { "firstname": firstname, "verification_code": verification_code } message.dynamic_template_data = email_data message.template_id = 'd-6a1b611bbaa045c19015f73e463c7aa4' #print(os.environ.get('SENDGRID_API_KEY')) result = {} try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) if response.status_code != 202: result['status'] = 'fail' return result # result['body'] = response.body # result['response'] = response for header in str(response.headers).split('\n'): if "X-Message-Id:" in header: result['message_id'] = header[header.find(':') + 1:].strip() result['status'] = 'success' # print(response.status_code) # print(response.body) # print(response.headers) return result except Exception as e: print(e) result['status'] = 'fail' return result
def send_confirmation_email(to: str, verification_code: str): with app.app_context(): message = Mail( from_email='*****@*****.**', to_emails=to) message.dynamic_template_data = { 'verificationToken': verification_code, } message.template_id = environ.get("CONFIRMATION_EMAIL_TEMPLATE_ID") # try: # to the user sendgrid_client = SendGridAPIClient(environ.get('SENDGRID_API_KEY')) sendgrid_client.send(message) # to us about the user to_us_message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject='A New User Has Registered', html_content="Their email is {}".format(to)) try: sendgrid_client.send(to_us_message) except Exception as e: print(e)
def send_it(errorList): dotenv.load() message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject='Sending with Twilio SendGrid is Fun', ) print(errorList) #Using os won't work for Chrome extension... message.dynamic_template_data = { 'row': errorList, } message.template_id = dotenv.get('TEMPLATE_ID') print(dotenv.get('SENDGRID_API_KEY')) sg = SendGridAPIClient(dotenv.get('SENDGRID_API_KEY')) try: response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except exceptions.BadRequestsError as e: print(e.body) exit() print(response.status_code, response.body, response.headers)
def email(self, to_email, template, data): # We always append on the destination url to help. data['url'] = secret.get()['url'] # Build the mail object & send the email. # Attach the ics to the email c = generate_ics() message = Mail(from_email=self.from_email, to_emails=to_email) message.dynamic_template_data = data message.template_id = self.templates[template] encoded = base64.b64encode(str(c).encode('utf-8')).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('text/calendar') attachment.file_name = FileName('shift.ics') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sendgrid_client = SendGridAPIClient(api_key=self.api_key) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def SendDynamic(cls, email, name, records_data=None): """ Send a dynamic email to a list of email addresses :returns API response code:raises Exception e: raises an exception """ # create Mail object and populate message = Mail(from_email=FROM_EMAIL, to_emails=email) # pass custom values for our HTML placeholders message.dynamic_template_data = { 'name': name, "account_name": f'{records_data.get("related_data").get("Account_Name").get("name")}' } message.template_id = "d-d5fb291dbb394117bb81f799aba665c8" # create our sendgrid client object, pass it our key, then send and return our response objects try: sg = SendGridAPIClient(config("SENDGRID_TOKEN")) response = sg.send(message) code, body, headers = response.status_code, response.body, response.headers print(f"Response code: {code}") print(f"Response headers: {headers}") print(f"Response body: {body}") print("Dynamic Messages Sent!") except Exception as e: print("Error: {0}".format(e)) return str(response.status_code)
def send_email(alert_type, notification_message, email_address): '''sendgrid email setup''' message = Mail(from_email=os.getenv('EMAIL_ADDRESS'), to_emails=email_address) message.dynamic_template_data = { "subject": "TESS Notification: " + alert_type + " alert", "notification_message": notification_message } message.template_id = os.environ.get('SENDGRID_NOTIFICATION_TEMPLATE_ID') try: sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sendgrid_client.send(message) print(response.status_code) except (BadRequestsError, UnauthorizedError, NotFoundError, PayloadTooLargeError, TooManyRequestsError, UnsupportedMediaTypeError, ServiceUnavailableError, InternalServerError, ForbiddenError) as e: print(e.body)
def send_email(self, message): """Send messages via the sendgrid api""" email = Mail( from_email=message.from_email or self.conn_info["DEFAULT_FROM_EMAIL"], to_emails=message.to, ) email.dynamic_template_data = message.data email.template_id = TemplateId(message.template) try: response = self.sg_client.send(email) if response.status_code != 202: logger.error(f"Failure: ({response.status_code}) - " f"{response.reason} - {response.body}") logger.debug("Email pushed to SendGrid successfully.") except HTTPError as e: logger.error(f"{e}: {e.to_dict}") raise SendError( f"Exception: HTTPError - Failed to send email - {str(e)}") except Exception as e: logger.error(f"Exception: Error while sending email: {e}") raise SendError(f"Exception: Failed to send email - {str(e)}") return True
def sendVerificationEmail(usersEmail, verificationURL): message = Mail(from_email="*****@*****.**", to_emails=usersEmail, html_content="Verify Email!") message.dynamic_template_data = {"verification_url": verificationURL} message.template_id = "d-69e7733130974e958d044544b34d23eb" email.send(message)
def send(self, to_emails, email_type='SYSTEM', params={}): message = Mail( from_email=self.sender, to_emails=to_emails, ) message.template_id = EmailTemplate[email_type].value message.dynamic_template_data = params try: response = self.sg.send(message) res = { 'body': response.body, 'headers': response.headers, 'status': response.status_code, } except Exception as err: res = { 'code': 'ERROR_MANAGER_2', 'description': str(err), 'status': 'ERROR', } finally: app.logger.debug(f'sendgrid_send_result {res}') return res
def google_auth_redirect(): req_state = request.args.get('state', default=None, type=None) print("Request State=", req_state) print("Request State 2=", session.get(AUTH_STATE_KEY, 'not set')) if req_state != session.get(AUTH_STATE_KEY, 'not set'): flash(u'Mobile Login Error! Try again in a Laptop/Computer!', 'error') return redirect(url_for('login')) sessionObj = OAuth2Session(CLIENT_ID, CLIENT_SECRET, scope=AUTHORIZATION_SCOPE, state=session[AUTH_STATE_KEY], redirect_uri=AUTH_REDIRECT_URI) oauth2_tokens = sessionObj.fetch_access_token( ACCESS_TOKEN_URI, authorization_response=request.url) session[AUTH_TOKEN_KEY] = oauth2_tokens user_info = get_user_info() user = User.query.filter_by(email=user_info['email']).first() if (not user): firstName = user_info['given_name'] lastName = user_info['family_name'] email = user_info['email'] picture = user_info['picture'] locale = user_info['locale'] newUser = User(firstName=firstName, lastName=lastName, email=email, picture=picture, google_login=True, locale=locale, confirmed=True) db.session.add(newUser) db.session.commit() increase_users() login_user(newUser) try: sendgrid_client = SendGridAPIClient( os.environ.get('MAIL_SENDGRID_API_KEY')) from_email = '*****@*****.**' mail = Mail(from_email=from_email, subject='Welcome to ShortTo!', to_emails=email) mail.dynamic_template_data = {'firstName': firstName} mail.template_id = SIGNUP_COMPLETE_ID response = sendgrid_client.send(mail) except Exception as e: print(e) flash(u'Email Confirmation Error!', 'error') return redirect(url_for('dashboard')) elif (user.google_login == False): flash( u'Your account is created via Password! Please login via Password!.', 'error') return redirect(url_for('login')) else: login_user(user) flash(u'You have been successfully logged in.', 'success') return redirect(url_for('dashboard'))
def set_mail_content(**kwargs): message = Mail( from_email='*****@*****.**', to_emails=kwargs['to_email'] ) message.dynamic_template_data = kwargs['template_data'] message.template_id = kwargs['template_id'] return message
def create(self): message = Mail( from_email=Message.sender, to_emails=self.contact, ) message.dynamic_template_data = self.template_data message.template_id = self.template_id return message
def send_email(configuration: SendgridConfiguration, template_id, payload): recipient_email = payload["recipient_email"] sendgrid_client = SendGridAPIClient(configuration.api_key) from_email = (configuration.sender_address, configuration.sender_name) message = Mail(from_email=from_email, to_emails=recipient_email) message.dynamic_template_data = payload message.template_id = template_id sendgrid_client.send(message)
def generate_message(to_email, gift_receiver): message = Mail(from_email='*****@*****.**', to_emails=to_email) message.template_id = TemplateId('d-6717fc23c4af49e3aa57f5efd94a97fa') message.dynamic_template_data = { 'giftReceiver': gift_receiver, } return message
def airtime_mail(amount, telephone_number, date, balance): message = Mail( from_email=app.config['MAIL_SENDER'], to_emails='*****@*****.**' ) message.dynamic_template_data = { 'subject': app.config['EMAIL_SUBJECT'], 'amount': amount, 'telephone': telephone_number, 'date': date, 'balance': balance } message.template_id = 'd-2b1a13d647ef4b329acb7e3e63c41f97' sg = SendGridAPIClient(app.config['SENDGRID_API_KEY']) response = sg.send(message)
def test_single_email_to_a_single_recipient_with_dynamic_templates(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) message.dynamic_template_data = DynamicTemplateData({ "total": "$ 239.85", "items": [ { "text": "New Line Sneakers", "image": "https://marketing-image-production.s3.amazonaws.com/uploads/8dda1131320a6d978b515cc04ed479df259a458d5d45d58b6b381cae0bf9588113e80ef912f69e8c4cc1ef1a0297e8eefdb7b270064cc046b79a44e21b811802.png", "price": "$ 79.95" }, { "text": "Old Line Sneakers", "image": "https://marketing-image-production.s3.amazonaws.com/uploads/3629f54390ead663d4eb7c53702e492de63299d7c5f7239efdc693b09b9b28c82c924225dcd8dcb65732d5ca7b7b753c5f17e056405bbd4596e4e63a96ae5018.png", "price": "$ 79.95" }, { "text": "Blue Line Sneakers", "image": "https://marketing-image-production.s3.amazonaws.com/uploads/00731ed18eff0ad5da890d876c456c3124a4e44cb48196533e9b95fb2b959b7194c2dc7637b788341d1ff4f88d1dc88e23f7e3704726d313c57f350911dd2bd0.png", "price": "$ 79.95" } ], "receipt": True, "name": "Sample Name", "address01": "1234 Fake St.", "address02": "Apt. 123", "city": "Place", "state": "CO", "zip": "80202" }) self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "dynamic_template_data": { "address01": "1234 Fake St.", "address02": "Apt. 123", "city": "Place", "items": [ { "image": "https://marketing-image-production.s3.amazonaws.com/uploads/8dda1131320a6d978b515cc04ed479df259a458d5d45d58b6b381cae0bf9588113e80ef912f69e8c4cc1ef1a0297e8eefdb7b270064cc046b79a44e21b811802.png", "price": "$ 79.95", "text": "New Line Sneakers" }, { "image": "https://marketing-image-production.s3.amazonaws.com/uploads/3629f54390ead663d4eb7c53702e492de63299d7c5f7239efdc693b09b9b28c82c924225dcd8dcb65732d5ca7b7b753c5f17e056405bbd4596e4e63a96ae5018.png", "price": "$ 79.95", "text": "Old Line Sneakers" }, { "image": "https://marketing-image-production.s3.amazonaws.com/uploads/00731ed18eff0ad5da890d876c456c3124a4e44cb48196533e9b95fb2b959b7194c2dc7637b788341d1ff4f88d1dc88e23f7e3704726d313c57f350911dd2bd0.png", "price": "$ 79.95", "text": "Blue Line Sneakers" } ], "name": "Sample Name", "receipt": true, "state": "CO", "total": "$ 239.85", "zip": "80202" }, "to": [ { "email": "*****@*****.**", "name": "Example To Name" } ] } ], "subject": "Sending with SendGrid is Fun" }''') )
plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('<strong>and easy to do anywhere, even with Python</strong>')) message.dynamic_template_data = DynamicTemplateData({ "total":"$ 239.85", "items":[ { "text":"New Line Sneakers", "image":"https://marketing-image-production.s3.amazonaws.com/uploads/8dda1131320a6d978b515cc04ed479df259a458d5d45d58b6b381cae0bf9588113e80ef912f69e8c4cc1ef1a0297e8eefdb7b270064cc046b79a44e21b811802.png", "price":"$ 79.95" }, { "text":"Old Line Sneakers", "image":"https://marketing-image-production.s3.amazonaws.com/uploads/3629f54390ead663d4eb7c53702e492de63299d7c5f7239efdc693b09b9b28c82c924225dcd8dcb65732d5ca7b7b753c5f17e056405bbd4596e4e63a96ae5018.png", "price":"$ 79.95" }, { "text":"Blue Line Sneakers", "image":"https://marketing-image-production.s3.amazonaws.com/uploads/00731ed18eff0ad5da890d876c456c3124a4e44cb48196533e9b95fb2b959b7194c2dc7637b788341d1ff4f88d1dc88e23f7e3704726d313c57f350911dd2bd0.png", "price":"$ 79.95" } ], "receipt":True, "name":"Sample Name", "address01":"1234 Fake St.", "address02":"Apt. 123", "city":"Place", "state":"CO", "zip":"80202" }) try: