本文整理汇总了Python中sendgrid.SendGridClient.send方法的典型用法代码示例。如果您正苦于以下问题:Python SendGridClient.send方法的具体用法?Python SendGridClient.send怎么用?Python SendGridClient.send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sendgrid.SendGridClient
的用法示例。
在下文中一共展示了SendGridClient.send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestSendGrid
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
class TestSendGrid(unittest.TestCase):
def setUp(self):
self.sg = SendGridClient(os.getenv('SG_USER'), os.getenv('SG_PWD'))
def test_send(self):
m = Mail()
m.add_to('John, Doe <[email protected]>')
m.set_subject('test')
m.set_html('WIN')
m.set_text('WIN')
m.set_from('[email protected]')
m.add_substitution('subKey', 'subValue')
m.add_section('testSection', 'sectionValue')
m.add_category('testCategory')
m.add_unique_arg('testUnique', 'uniqueValue')
m.add_filter('testFilter', 'filter', 'filterValue')
m.add_attachment_stream('testFile', 'fileValue')
self.sg.send(m)
url = self.sg._build_body(m)
url.pop('api_key', None)
url.pop('api_user', None)
url.pop('date', None)
test_url = json.loads('''
{
"to[]": ["[email protected]"],
"toname[]": ["John Doe"],
"html": "WIN",
"text": "WIN",
"subject": "test",
"files[testFile]": "fileValue",
"from": "[email protected]",
"headers": "",
"fromname": "",
"replyto": ""
}
''')
test_url['x-smtpapi'] = json.dumps(json.loads('''
{
"sub": {
"subKey": ["subValue"]
},
"section": {
"testSection":"sectionValue"
},
"category": ["testCategory"],
"unique_args": {
"testUnique":"uniqueValue"
},
"filters": {
"testFilter": {
"settings": {
"filter": "filterValue"
}
}
}
}
'''))
self.assertEqual(url, test_url)
示例2: send_email
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def send_email(report, title):
API_KEY = os.environ.get('SENDGRID_KEY')
if API_KEY is None:
print 'No SendGrid API key found! Please set the SENDGRID_KEY env var'
sys.exit(1)
sg = SendGridClient(API_KEY, raise_errors=True)
# Backwards compatability for emails stored as strings, not lists
emails = report['project_details']['email']
if type(emails) is not list:
emails = [emails]
for address in emails:
message = Mail()
message.add_to(address)
message.set_subject(title)
message.set_html(generate_email_text(report))
message.set_from('STACKS <[email protected]>')
try:
sg.send(message)
except SendGridError as e:
print e
except SendGridClientError as e:
print e
except SendGridServerError as e:
print e
示例3: sendEmail
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def sendEmail(sender, recipient, subject, html, text) :
sg= SendGridClient('ecpf', 'Iheart1!', secure=True)
message = Mail()
message.set_subject(subject)
message.set_html(html)
message.set_text(text)
message.set_from(sender)
message.add_to(recipient)
sg.send(message)
return True
示例4: EmailClient
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
class EmailClient(object):
def __init__(self):
self.sg = SendGridClient(SG_API_KEY)
self.message = Mail()
self.message.set_from(SG_FROM)
self.message.set_from_name(SG_FROM_NAME)
def send_sg_email(self, correo):
# valores de envío
self.message.add_to(correo.correo)
self.message.add_to_name(correo.nombre_cliente)
self.message.set_subject(correo.asunto)
self.message.set_html(correo.html)
# valores personalizados
unique_args = {
'empresa': correo.empresa,
'rut_receptor': correo.rut_receptor,
'rut_emisor': correo.rut_emisor,
'tipo_envio': correo.tipo_envio,
'tipo_dte': correo.tipo_dte,
'numero_folio': correo.numero_folio,
'resolucion_receptor': correo.resolucion_receptor,
'resolucion_emisor': correo.resolucion_emisor,
'monto': correo.monto,
'fecha_emision': correo.fecha_emision,
'fecha_recepcion': correo.fecha_recepcion,
'estado_documento': correo.estado_documento,
'tipo_operacion': correo.tipo_operacion,
'tipo_receptor': correo.tipo_receptor,
}
self.message.set_unique_args(unique_args)
# Validacion de adjuntos
if correo.attachs:
for adjunto in correo.attachs:
adj = AttachModel.query(ancestor=adjunto).get()
self.message.add_attachment_stream(adj.nombre, adj.archivo)
# enviando el mail
status, msg = self.sg.send(self.message)
# imprimiendo respuesta
logging.info(status)
logging.info(msg)
def send_mail_to_user_attach(self, correo):
# valores de envío
self.message.add_to(correo['email'])
self.message.add_to_name(correo['user_name'])
self.message.set_subject(correo['subject'])
self.message.set_html(correo['html'])
if correo['attach']:
self.message.add_attachment_stream(correo['attach']['name'], correo['attach']['file'])
status, msg = self.sg.send(self.message)
# imprimiendo respuesta
logging.info(status)
logging.info(msg)
示例5: SGEmailClient
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
class SGEmailClient(object):
def __init__(self):
self.email_config = SendGridConfiguration.objects.all()[:1].get()
self.sg = SendGridClient(self.email_config.api_key)
self.message = Mail()
self.message.set_from(self.email_config.email_from)
self.message.set_from_name(self.email_config.email_from_name)
self.message.set_subject(self.email_config.email_subject)
def send_report_email(self, email, report):
template_config = TemplateReport.objects.all()[:1].get()
user = get_object_or_404(User, pk=email)
logger.info(user)
html = unicode(template_config.html_template).format(
user_name=user.first_name,
)
self.message.add_to(user.email)
self.message.add_to_name(user.first_name)
self.message.set_html(html)
if report['report']:
self.message.add_attachment_stream(
report['name'] , report['report']
)
status, msg = self.sg.send(self.message)
logger.info('{0} - {1}'.format(status, msg))
示例6: test_emails
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def test_emails():
test_emails = ['[email protected]']
all_shows = shows_this_week()
text = all_shows_to_markdown(all_shows)
html = markdown(text)
today, next_week = week_interval()
tomorrow = today + relativedelta(days=+1)
date_format = "%m/%d"
responses = []
# make a secure connection to SendGrid
sg = SendGridClient(SENDGRID_USER, SENDGRID_PASSWORD, secure=True)
for email in test_emails:
# make a message object
message = Mail()
message.set_subject('NYC Jazz Digest: {} to {}'.format(tomorrow.strftime(date_format), next_week.strftime(date_format)))
message.set_html(html)
message.set_text(text)
message.set_from('NYC Jazz Digest <[email protected]>')
# add a recipient
message.add_to(email)
# use the Web API to send your message
responses.append(str(sg.send(message)))
return '\n'.join(responses)
示例7: send_digest
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def send_digest():
sg = SendGridClient(SENDGRID_USER, SENDGRID_PASSWORD, secure=True)
responses = []
today, next_week = week_interval()
tomorrow = today + relativedelta(days=+1)
date_format = "%m/%d"
subject = 'NYC Jazz Digest: {} to {}'.format(tomorrow.strftime(date_format), next_week.strftime(date_format))
from_addr = 'NYC Jazz Digest <[email protected]>'
all_shows = shows_this_week()
text = all_shows_to_markdown(all_shows)
for user in User.query(User.opt_out == False).fetch():
unsubcribe_link = ROOT_URL + '/unsubscribe/' + user.uuid
unsubscribe_phrase = "\n\nClick [here]({}) to unsubscribe.".format(unsubcribe_link)
text += unsubscribe_phrase
html = markdown(text)
message = Mail()
message.set_subject(subject)
message.set_html(html)
message.set_text(text)
message.set_from(from_addr)
# add a recipient
message.add_to(user.email)
# use the Web API to send your message
responses.append(str(sg.send(message)))
return '\n'.join(responses)
示例8: SendgridNotificationService
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
class SendgridNotificationService(BaseNotificationService):
def __init__(self, api_key, sender, recipient):
self.api_key = api_key
self.sender = sender
self.recipient = recipient
from sendgrid import SendGridClient
self._sg = SendGridClient(self.api_key)
def send_message(self, message='', **kwargs):
subject = kwargs.get(ATTR_TITLE)
from sendgrid import Mail
mail = Mail(from_email=self.sender, to=self.recipient,
html=message, text=message, subject=subject)
self._sg.send(mail)
示例9: send_revocation_request_email
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def send_revocation_request_email(cfg, keyid, hex, user_email):
# Send message using sendgrid api
client = SendGridClient(cfg.config.sendgrid.api_key)
message = get_sendgrid_request_message(cfg, keyid, hex, user_email)
response = client.send(message)
# Return JSON success message (response[1]) and HTTP status (response[0])
return response[1], response[0]
示例10: send_email
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def send_email(self, request):
# make a secure connection to SendGrid
sg = SendGridClient(get_mail_username(), get_mail_pass(), secure=True)
# make a message object
message = Mail()
message.set_subject('message subject')
message.set_html('<strong>HTML message body</strong>')
message.set_text('plaintext message body')
message.set_from('[email protected]')
# add a recipient
message.add_to('John Doe <[email protected]>')
# use the Web API to send your message
sg.send(message)
return message_types.VoidMessage()
示例11: recieve_result
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def recieve_result():
account_sid = "ACe36f8844f05de80021faa460764b6d33"
auth_token = "f22d67391209d2a4f8f54266cd721978"
client = TwilioRestClient(account_sid, auth_token)
global numberTwo
value = request.form
fromValue = value.get("From")
bodyValue = value.get("Body")
toValue = value.get("To")
# print "Body: " + bodyValue
# print "From: " + fromValue
# print "To: " + toValue
value = "True"
if str(bodyValue) == "An outage was reported in your area. We expect this to be resolved by 6pm today.":
value = "False"
elif str(bodyValue).strip().lower() == "yes":
value = "yes"
if value == "True":
htmlForEmail = '<html><body><img src="http://wedte.com/wp-content/uploads/2013/01/PowerOutage.jpg" alt="Power Outage"><p></p><p></p><h3> We think that your house may have a power outage. If this is true, simply reply to this e-mail with any response so that the Electricty Supplier can serve you faster. <p></p><br><br></h3></body></html>'
sg = SendGridClient(SendGridUserName, SendGridPassword)
message = Mail()
message.add_to(emailValue)
message.set_subject("Is there a Power Outage at your house?")
message.set_html(htmlForEmail)
message.set_from(FromEmail)
status, msg = sg.send(message)
message = client.messages.create(
body="We think that your house may have a power outage. If this is true, simply reply to this text with a 'yes' so that the Electricty Supplier can serve you faster.",
to=str(personalNumber), # Replace with your phone number
from_=str(number),
) # Replace with your Twilio number
elif value == "yes":
value = "True"
elif value == "no":
value = "False"
payload = {"powerOutage": value, "twilioNumber": number}
r = requests.post("http://ec2-54-68-73-74.us-west-2.compute.amazonaws.com:5000/powerreply", data=payload)
numberTwo = number
print str(value)
print numberTwo
return "Test"
示例12: SendgridNotificationService
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
class SendgridNotificationService(BaseNotificationService):
"""Implement the notification service for email via Sendgrid."""
def __init__(self, api_key, sender, recipient):
"""Initialize the service."""
self.api_key = api_key
self.sender = sender
self.recipient = recipient
from sendgrid import SendGridClient
self._sg = SendGridClient(self.api_key)
def send_message(self, message='', **kwargs):
"""Send an email to a user via SendGrid."""
subject = kwargs.get(ATTR_TITLE)
from sendgrid import Mail
mail = Mail(from_email=self.sender, to=self.recipient,
html=message, text=message, subject=subject)
self._sg.send(mail)
示例13: send_email
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def send_email(name: str, address: str, subject: str, template: str, values: dict) -> bool:
sg = SendGridClient(config.SENDGRID_API_USER, config.SENDGRID_API_KEY)
mail = Mail()
mail.set_from('tototo <[email protected]>')
mail.add_to(name + ' <' + address + '>')
mail.set_subject(subject)
mail.set_html(render_template(template, **values))
status, _ = sg.send(mail)
return status == 200
示例14: threshold_not_met
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def threshold_not_met(petitioner_id, organization, election, threshold, signatures, position, petition_email, admin_emails):
petitioner = netid2name(petitioner_id)
# Make a secure connection to SendGrid
sg = SendGridClient('harmonica1243', 'xqBrrnNqbGuvtEUpNRs3RePW', secure=True)
# Replace with the message that we want to send, such as the name of the person and the position
html_petition = '<p style="text-align: left;"><b>Dear ' + petitioner + ',</b></p><p style="text-align: center;">' \
'<p>Your petition no longer has the required number of signatures</p><ul><li><b>Organization:</b> ' \
+ organization + '</li><li><b>Election:</b> ' + election + '</li><li><b>Position:</b> ' + position + '</li>' \
'<li><b>Number of Signatures Required:</b> ' + threshold + '</li><li><b>Number of Signatures Obtained:</b> ' \
+ signatures + '</li></ul><p>Please contact the organization directly with any questions about the petition.' \
'</p></p><p style="text-align: left;"><b>Rice Apps Petitions</b></p>'
html_admin = '<p style="text-align: left;"><b>Dear Organization Administrator,</b></p><p style="text-align: center;">' \
'<p>This petition no longer has the required number of signatures</p><ul><li><b>Petition Creator:</b> ' \
+ petitioner + '</li><li><b>Organization:</b> ' + organization + '</li><li><b>Election:</b> ' + election + \
'</li><li><b>Position:</b> ' + position + '</li><li><b>Number of Signatures Required:</b> ' + threshold + \
'</li><li><b>Number of Signatures Obtained:</b> ' + signatures + '</li></ul><p>Please contact ' + ADMIN_ID + \
'@rice.edu with any questions.</p></p><p style="text-align: left;"><b>Rice Apps Petitions</b></p>'
# Make a message Object
message = Mail()
# Message Subject, Body and To
message.set_subject('Petition No Longer Has Enough Signatures')
message.set_html(html_petition)
message.set_from('[email protected]')
message.add_to('<' + petition_email + '>')
sg.send(message)
# Make a message Object
message = Mail()
# Message Subject, Body and To
message.set_subject('Petition No Longer Has Enough Signatures')
message.set_html(html_admin)
message.set_from('[email protected]')
for email in admin_emails:
message.add_to('<' + email + '>')
sg.send(message)
示例15: send_email
# 需要导入模块: from sendgrid import SendGridClient [as 别名]
# 或者: from sendgrid.SendGridClient import send [as 别名]
def send_email(subject='Test email', from_email='[email protected]', from_name='D. Goodwin', recipients=['[email protected]'], text_body='Hello from Flask', html_body='Hello from <b>Flask</b>'):
from sendgrid import SendGridClient, Mail
api_key = 'm3tr0pl4c3s'
api_user = 'metroplaces'
sendgrid = SendGridClient(username=api_user, password=api_key,
raise_errors=True,
host='http://api.sendgrid.com',
port=80,
)
message = Mail()
message.add_to(recipients)
message.set_from(from_email)
message.set_from_name(from_name)
message.set_subject(subject)
message.set_text(text_body)
message.set_html(html_body)
try:
sendgrid.send(message)
except Exception as e:
print "fail: %s" %(e)