def send_email(self): # send email using the self.cleaned_data dictionary first_name = self.cleaned_data.get("fname") last_name = self.cleaned_data.get("lname") email = self.cleaned_data.get("email") phone = self.cleaned_data.get("phone") message = self.cleaned_data.get("message") # Issue response to client via sendgrid API sendgrid_client = SendGridAPIClient(config('SENDGRID_API_KEY')) mail = Mail() mail.from_email = From(config('EMAIL_FROM')) mail.to_email = To(email) mail.subject = "Your Enquiry with Mayan Web Studio" mail.template_id = config('SENDGRID_TEMPLATE_ID') p = Personalization() p.add_to(To(email)) p.dynamic_template_data = { "firstName": first_name, "lastName": last_name, "phone": phone } mail.add_personalization(p) response = sendgrid_client.client.mail.send.post( request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) # Send notification email to Mayan subject, from_email, to = 'New Enquiry for Mayan Web Studio', config( 'EMAIL_FROM'), '*****@*****.**' text_content = 'This is an important message.' html_content = ''' <h3>New Enquiry from</h3> <ul> <li>First Name: $(first_name)</li> <li>Last Name: $(last_name)</li> <li>Email: $(email)</li> <li>Phone: $(phone)</li> <li>Message: $(message)</li> </ul> ''' html_content = html_content.replace("$(first_name)", first_name) html_content = html_content.replace("$(last_name)", last_name) html_content = html_content.replace("$(email)", email) html_content = html_content.replace("$(phone)", phone) html_content = html_content.replace("$(message)", message) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send()
def test_send_a_single_email_to_multiple_recipients(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None to_emails = [ To('*****@*****.**', 'Example To Name 0'), To('*****@*****.**', 'Example To Name 1') ] message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=to_emails, 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>')) 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": [ { "to": [ { "email": "*****@*****.**", "name": "Example To Name 0" }, { "email": "*****@*****.**", "name": "Example To Name 1" } ] } ], "subject": "Sending with SendGrid is Fun" }'''))
def create_message(today, job, template): from_email = From('*****@*****.**', 'junior.guru') to_email = To('*****@*****.**', job.company_name) # TODO job.email subject = f'Jak se daří vašemu inzerátu? ({job.title})' starts_at = job.effective_approved_at ends_at = job.expires_at or (today + timedelta(days=30)) content = template.render( title=job.title, company_name=job.company_name, url=f'https://junior.guru/jobs/{job.id}/', metrics=job.metrics, starts_at=starts_at, start_days=(today - starts_at).days, ends_at=ends_at, end_days=(ends_at - today).days, newsletter_at=job.newsletter_at, newsletter_url= 'https://us3.campaign-archive.com/home/?u=7d3f89ef9b2ed953ddf4ff5f6&id=e231b1fb75' ) return Mail(from_email=from_email, to_emails=to_email, subject=subject, html_content=content)
def construct_email(primitives, server_addr, my_addr): """Tries to build an email from the information in the request. :param primitives: The raw request information. :param server_addr: The email address of the server. :param my_addr: My email address. :return """ # Validate input for (key, item) in primitives.items(): if item is None: raise ContactInfoException( msg="Missing attribute: \"{}\"".format(key)) if not isinstance(item, str) or not len(item) > 0: raise ContactInfoException( msg="Attribute \"{}\" must be a nonempty string".format(key)) # Construct body of message tz = timezone("EST") text = "Name: {}\n".format(primitives["name"]) text += "Organization: {}\n".format(primitives["org"]) text += "Email: {}\n".format(primitives["email"]) text += "{}UTC\n".format(datetime.datetime.utcnow()) text += "{}EST\n".format(datetime.datetime.now(tz)) text += "---------------------\n" text += "Message: {}\n".format(primitives["msg"]) # Construct email body = Content("text/plain", text) subj = "Someone used the form!" server_email = Email(server_addr) my_email = To(my_addr) return Mail(server_email, my_email, subj, body)
def make_email(self, fromaddr, fromname, toaddr, toname, subject, content): return Mail( SendgridEmail(email=fromaddr, name=fromname), To(email=toaddr, name=toname), subject, self.build_content(toname, content) )
def notify_email(cls, email, name, records_data): from_email = Email(FROM_EMAIL) to_email = To(email) subject = f'You have been assigned to account : {records_data.get("related_data").get("Account_Name").get("name")}' content = Content( "text/html", f""" <img src="https://i.ibb.co/X4xqHkW/logo.png" alt="Yodo1 Fish"> <p> <h2>Dear <span style="color:black;font-weight:bold">{name}</span>,</h2> </p> <p> Following the change of stage to <span style="color:black;font-weight:bold">Closed (Won)</span> in the {records_data.get("related_data").get("Account_Name").get("name")} you have been automatically assigned to it. </p> <br> The Yodo1 Developer Support Team """) try: mail = Mail(from_email, to_email, subject, content) mail_json = mail.get() sg = SendGridAPIClient(config("SENDGRID_TOKEN")) response = sg.client.mail.send.post(request_body=mail_json) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def sendMailWithPdf(email): #mailMsg = '{ # "subject": "subject", # "to": "*****@*****.**", # "from": "*****@*****.**", # "text": "Text", # "html": "", # "filename": "stats.xlsx", # "contentId": "stats" #}' #mailMsgJson = json.loads(mailMsg) message = Mail() message.to = To(email.data['to']) message.subject = Subject(email.data['subject'], p=0) message.from_email = From(email.data['from'], 'My Team Manager') message.template_id = TemplateId(email.data['templateId']) message.attachment = Attachment(FileContent(email.data['pdf']), FileName(email.data['filename']), FileType('application/pdf'), Disposition('attachment'), ContentId('Content ID 1')) message.content = Content(MimeType.text, email.data['text']) message.content = Content(MimeType.html, email.data['html']) sg = SendGridAPIClient(mailApiKey) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers)
def emailDictToToList(emailDict): emailsList = [] for email in emailDict: toEmail = To(email=email, substitutions={'[-project-]': emailDict[email]}) emailsList.append(toEmail) return emailsList
def success(request): verify_response_headers(request.GET, PAYTRAIL_ACCOUNT_SECRET, "") checkout_transaction_id = request.GET["checkout-transaction-id"] logger.info("Success for transaction %s %s", checkout_transaction_id) transaction = Transaction.objects.get( checkout_transaction_id=checkout_transaction_id) donor_email = transaction.contribution.donor.email donation_sum = transaction.contribution.sum if transaction.confirmation_email_sent == False: logger.info("Sending confirmation email to %s", donor_email) confirmation_email = Mail( from_email=sendgrid_from_email, to_emails=To( donor_email, dynamic_template_data={ "sum_as_concrete": str(round(donation_sum / 180, 2)), "sum_as_dance_floor": str(round(10_000 * donation_sum / 4815)), "sum_as_percentage": str(round(100 * donation_sum / 6_500_00, 4)), "link_to_donation": f"{FRONTEND_URL}/donation?betalning=ok&checkout-transaction-id={checkout_transaction_id}" }))
def send_reset_password_email(self, user, challenge): """ :param User user: :param str challenge: """ query = urlencode({ 'email': user.email, 'challenge': challenge, 'verification_code': user.reset_password_token, }) env = { 'url': f'{PROJECT_URL}/enter-verification-code?{query}', 'name': user.name, 'company': user.company, 'reset_password_token': user.reset_password_token, } body = RESET_PASSWORD_TEMPLATE % env from_email = Email(EMAIL_FROM_ADDRESS, EMAIL_FROM_NAME) to_email = To(user.email) subject = 'Reset password' content = Content('text/plain', body) mail = Mail(from_email, to_email, subject, content) self.client.client.mail.send.post(request_body=mail.get())
def send_welcome_email(self, user, challenge): """ :param User user: :param str challenge: """ query = urlencode({ 'email': user.email, 'challenge': challenge, 'activate_token': user.activate_token, }) env = { 'url': f'{PROJECT_URL}/verify-email?{query}', 'name': user.name, 'company': user.company, } body = WELCOME_TEMPLATE % env from_email = Email(EMAIL_FROM_ADDRESS, EMAIL_FROM_NAME) to_email = To(user.email) subject = 'Activate your account' content = Content('text/plain', body) mail = Mail(from_email, to_email, subject, content) self.client.client.mail.send.post(request_body=mail.get())
def send_email(recipients, subject, text_body, html_body, send_admin=False): message = Mail() msg_to = [] for r in recipients: msg_to.append(To(r)) message.to = msg_to if send_admin: admin_list = current_app.config['MAIL_ADMINS'].split(';') msg_bcc = [] for a in admin_list: msg_bcc.append(Bcc(a)) message.bcc = msg_bcc message.subject = Subject(subject) message.from_email = From(current_app.config['MAIL_FROM'], 'Indian Matrimonial') message.reply_to = ReplyTo(current_app.config['MAIL_REPLY_TO'], 'Indian Matrimonial') message.content = [ Content('text/html', html_body), Content('text/txt', text_body) ] try: sg = SendGridAPIClient(current_app.config['SENDGRID_API_KEY']) response = sg.send(message) print(response.status_code), print(response.body) print(response.headers) return True except Exception as e: print(e) return False
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 welcome_mail(sender, instance, **kwargs): if kwargs["created"]: user_email = instance.email sg = sendgrid.SendGridAPIClient(api_key=config("SENDGRID_API_KEY")) from_email = Email("*****@*****.**") to_email = To(user_email) subject = "Welcome to contractAlchemy!" content = Content( "text/plain", "contractAlchemy is a tool that organizes your clients, jobs, parts, and invoices " "all in one convenient place. The first step in using our application is to " "create a client. Once you've done that, you can start to build out the jobs " "that fall under that client, adding any parts that contribute to that job." "Those parts are what's used in building out invoices for your customers.\n\n" "Premium users gain access to all of our features with an unlimited number of " "records. Premium membership also includes the ability to select different " "themes for the website.\n\n" "Free membership includes access to all of our features (outside theme switching) " "for up to 6 records of a type at a given type (6 clients, 6 jobs, etc.). You " "can upgrade to premium membership at any time in the billing section - monthly " "subscriptions are $0.99 per month and yearly subscriptions are $9.99.\n\n" "We hope this makes your life at least a little bit easier.\n\n" "Thank you for joining", ) mail = Mail(from_email, to_email, subject, content) sg.client.mail.send.post(request_body=mail.get())
def construct_mail(self, emails: List[str], content: str) -> Mail: """Returns a Mail object that can be posted to the SendGrid API's email sending endpoint. Args: emails (List[str]): List of emails to add 'To' header content (str): String of content to add to the email body Mail: Completed Mail object capable of being sent Returns: sendgrid.helpers.mail.Mail() """ current_date = date.today().strftime("%B %d, %Y") subject = Subject(f"DevOps Now hours usage as of {current_date}") content = Content("text/plain", content) to_emails = [To(email=email) for email in emails] from_email = Email(self.from_email) message = Mail( from_email=from_email, to_emails=to_emails, subject=subject, plain_text_content=content, ) return message
def post(self): # send an email to my email address with the relevant details details = [value for key, value in request.form.items()] name = details[0] to_email = To("*****@*****.**") from_email = Email("*****@*****.**", name="Online Life Calendar") subject = "New Contact Message from Life Calendar" content = Content( "text/plain", f""" Hi Simon, you had someone contact you through the automated messaging service at onlinelifecalendar.com. You can view the details below: Name: {details[0]} Email Address: {details[1]} Subject: {details[2]} Message: {details[3]} Make sure to get back to them soon! """) Thread(target=self.send_contact_mail, args=(from_email, to_email, subject, content)).start() return redirect(url_for("ThanksView:index", name=name))
def send_email(request, pk): form = get_object_or_404(Form, pk=pk) re_captcha_is_valid = re_captcha(request, form.re_captcha) if not re_captcha_is_valid: return Response(status=status.HTTP_403_FORBIDDEN) reply_to = request.POST.get("_replyTo") or form.reply_to content = get_form_content(request.POST) message = Mail( from_email=From(settings.FROM_EMAIL, form.from_name), to_emails=To(form.to), subject=Subject(form.subject), html_content=content, ) message.reply_to = ReplyTo(reply_to) if form.cc: message.cc = get_emails(form.cc) if form.bcc: message.bcc = get_emails(form.bcc) try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) return Response(status=status.HTTP_200_OK) except Exception as e: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def send_email(receiver_email, text_message, job_number, test=False): """Sends an e-mail from `[email protected] over SMTP protocol. Parameters: - `receiver_email` (dict {str:str}): keys are contact names and values are contact email addresses. This specifies the recipient(s) of the email. - `html_message` (str): text contained in the email. - `job_number` (str): user's job number. - `test`: if set to `True`, will short-circuits out of function without doing anything. """ message = Mail(to_emails=[*receiver_email.values()], subject=f"Upcoming Holdback Release: #{job_number}", html_content=text_message) message.from_email = From('*****@*****.**', 'HBR-Bot Notifier') message.to_email = To([*receiver_email.values()]) if test: return # escape early try: with open(".secret.json") as f: api_key = json.load(f)["sendgrid_key"] sg = SendGridAPIClient(api_key) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message)
def build_email(message): print("Iniciando envio de email para aviso") email_subject = Subject("SmartScale") email_address = To("*****@*****.**") from_email = From("*****@*****.**") email_content = "Olá, esta é uma mensagem automática da sua SmartScale\n\n\n" + message send_email(email_address, email_subject, email_content, from_email)
def send(to_email, subject, html_content): """Send email.""" sendgrid_api_key = db_config.get_value('sendgrid_api_key') if not sendgrid_api_key: logs.log_warn( 'Skipping email as SendGrid API key is not set in config.') return from_email = db_config.get_value('sendgrid_sender') if not from_email: logs.log_warn( 'Skipping email as SendGrid sender is not set in config.') return message = Mail(from_email=From(str(from_email)), to_emails=To(str(to_email)), subject=Subject(subject), html_content=HtmlContent(str(html_content))) try: sg = SendGridAPIClient(sendgrid_api_key) response = sg.send(message) logs.log('Sent email to %s.' % to_email, status_code=response.status_code, body=response.body, headers=response.headers) except Exception: logs.log_error('Failed to send email to %s.' % to_email)
def _prepare_message(self, message: EmailSchema) -> Mail: from_email = Email(message.from_email or self.settings.DEFAULT_EMAIL_ADDRESS) to_email = To(message.to_email) subject = message.subject content = Content(message.content_type, message.content) return Mail(from_email, to_email, subject, content)
def send_email(to_email, subject, body, from_email=FROM_EMAIL, html=True): from_email = From(email=from_email, name=PYBITES) to_email = To(to_email) # if local no emails if settings.LOCAL: body = body.replace('<br>', '\n') print('local env - no email, only print send_email args:') print(f'to_email: {to_email.email}') print(f'subject: {subject}') print(f'body: {body}') print(f'from_email: {from_email.email}') print(f'html: {html}') print() return # newlines get wrapped in email, use html body = body.replace('\n', '<br>') message = Mail(from_email=from_email, to_emails=to_email, subject=subject, plain_text_content=body if not html else None, html_content=body if html else None) response = sg.send(message) if str(response.status_code)[0] != '2': # TODO logging print(f'ERROR sending message, status_code {response.status_code}') return response
def email_server(): print('sending email...') print(request.args) arg1 = request.args.get('to', type=str) arg2 = request.args.get('payload', type=str) #Exercise 2 message = Mail(from_email='*****@*****.**', to_emails=To(arg1), subject=arg2, html_content='<p>' + arg2 + '</p>') try: sg = SendGridAPIClient( "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" ) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.body) print(e.reason) if arg1 is None or arg2 is None: return 'Error: Missing parameters' else: return 'to=' + arg1 + ', payload=' + arg2
def get_recipients(): emails = config.get_emails() to_list = Personalization() for email in emails: to_list.add_to(To(email)) return to_list
def post(self): """Reset user password""" email = api.payload["email"] user = User.query.filter(User.email == email).first() if user is None: raise UserDoesNotExist if user.blocked: raise BlockedUser new_pass = generate_random_password(DEFAULT_RESET_PWD_LEN) user.password = new_pass db.session.merge(user) db.session.commit() sg = sendgrid.SendGridAPIClient(api_key=config.sendgrid.api_key()) email = config.reset_pwd_email(default=DEFAULT_RESET_PWD_EMAIL) from_email = Email(email) to_email = To(user.email) subject = "BookBNB - Password Reset" content_body = f"Your password has been reset. Your new password is: {new_pass}" content = Content("text/plain", content_body) mail = Mail(from_email, to_email, subject, content) mail_json = mail.get() sg.client.mail.send.post(request_body=mail_json) return {"status": "success"}, 201
def register(): if current_user.is_authenticated: return redirect(url_for('user.welcome')) form = RegisterForm() if form.validate_on_submit(): if not form.validate_username(form.username): flash('Username has been registered, please choose another name.') return redirect(url_for('user.register')) if not form.validate_email(form.email): flash('Email has been registered, please choose another one.') return redirect(url_for('user.register')) register_user = User(name=str(form.username.data), email=str(form.email.data), contact=str(form.contactnumber.data), address=str(form.homeaddress.data), extra_info=str(form.extrainfo.data)) register_user.set_password(form.password.data) db.session.add(register_user) db.session.commit() flash('Register Successfully!') # sending emails from verified email address sender = From('*****@*****.**') to = To(str(form.email.data)) subject = "Welcome to Beauty Care!" content = Content('text/html', f'<b>Welcome! {form.username.data}</b>. <br> ' f'<p>You have registered successfully in Beauty Health Care.</p>' f'<p>Looking forward to see you!</p>' f'<p>------</p>' f'<p>Best wishes,</p>' f'<p>Betty</p>') mail = Mail(from_email=sender, subject=subject, to_emails=to, html_content=content) thr = Thread(target=sg.client.mail.send.post, args=[mail.get()]) thr.start() return redirect(url_for('user.register')) return render_template('register.html', form=form)
def sendgrid_handler(self, queue_message, to_addrs_to_email_messages_map): self.logger.info("Sending account:%s policy:%s %s:%s email:%s to %s" % ( queue_message.get('account', ''), queue_message['policy']['name'], queue_message['policy']['resource'], str(len(queue_message['resources'])), queue_message['action'].get('template', 'default'), to_addrs_to_email_messages_map)) from_address = self.config.get('from_address', '') subject = get_message_subject(queue_message) email_format = queue_message['action'].get('template_format', None) if not email_format: email_format = queue_message['action'].get( 'template', 'default').endswith('html') and 'html' or 'plain' for email_to_addrs, message in six.iteritems(to_addrs_to_email_messages_map): for to_address in email_to_addrs: if email_format == "html": mail = Mail( from_email=From(from_address), to_emails=To(to_address), subject=subject, html_content=message.as_string()) else: mail = Mail( from_email=From(from_address), to_emails=To(to_address), subject=subject, plain_text_content=message.as_string()) try: self.sendgrid_client.send(mail) except (exceptions.UnauthorizedError, exceptions.BadRequestsError) as e: self.logger.warning( "\n**Error \nPolicy:%s \nAccount:%s \nSending to:%s \n\nRequest body:" "\n%s\n\nRequest headers:\n%s\n\n mailer.yml: %s" % ( queue_message['policy'], queue_message.get('account', ''), email_to_addrs, e.body, e.headers, self.config ) ) return False return True
def __init__(self, to_email, subject, content): if len(content) != 2: raise TypeError( f"__init__() content aceita apenas 2 parâmetros mas {len(content)} foram dados" ) self.to_email = To(to_email) self.subject = subject self.content = Content(*content)
def send_email(subject, message, to_email): target = To(to_email) # content = Content('text/html', message) mail = Mail(from_email=from_email, to_emails=[target], subject=subject, plain_text_content=message) response = sg.client.mail.send.post(request_body=mail.get()) print('SendGrid response:' + str(response.status_code))
def send(recipients: Union[Tuple[Tuple[str, str]], Tuple[str, str]], subject: str, body_html: Optional[str], body_text: str) -> bool: """Send an email from the configured address. `recipients` is a list of tuples like `[(address, name),...]` or just a single tuple like `(address, name)`. Does not check for address validity. If `body_text` is None, it will be derived from `body_html`. if `body_html` is None but `body_text` is provided, no HTML part will be sent. Returns True on success, false otherwise. Does not throw exception. """ if config.DEMO: # Emails to users are disabled to prevent abuse. return True if not recipients: return True if isinstance(recipients[0], str): # We were passed just `(address, name)`.s recipients = [recipients] if not body_text and not body_html: raise Exception( 'emailer.send: body_text or body_html must be provided') elif body_html and not body_text: h2t = html2text.HTML2Text() h2t.body_width = 0 body_text = h2t.handle(body_html) sg = SendGridAPIClient(api_key=config.SENDGRID_API_KEY) to = [] for r in recipients: to.append(To(r[0], r[1])) message = Mail(from_email=From(config.MASTER_EMAIL_SEND_ADDRESS, name=config.MASTER_EMAIL_SEND_NAME), to_emails=to, subject=Subject(subject), plain_text_content=PlainTextContent(body_text), html_content=HtmlContent(body_html) if body_html else None) response = sg.client.mail.send.post(request_body=message.get()) if response.status_code not in (200, 202): # The expected response code is actually 202, but not checking for 200 as well feels weird. logging.error( f"emailer.send fail: {response.status_code} | {response.body} | {response.headers}" ) return False # Body is expected to be empty on success, but we'll check it anyway. logging.info( f"emailer.send success: {response.status_code} | {response.body}") return True