def send(self, message): """ Send message Args: message: Sendgrid Message object Returns: True on success Raises: SGServiceException: on error """ # Compose the message. If there are two bodies we need to create two # mime entities, otherwise we send one message if (message.text and message.html) or message.attachments: email_message = MIMEMultipart('alternative') if message.text: email_message.attach( self._getMessageMIME(message.text, 'plain')) if message.html: email_message.attach(self._getMessageMIME( message.html, 'html')) elif message.text: email_message = self._getMessageMIME(message.text, 'plain') else: email_message = self._getMessageMIME(message.html, 'html') email_message['From'] = self._encodeEmail(message.from_name, message.from_address) if message.to_name: email_message['To'] = ', '.join([ self._encodeEmail(message.to_name[i], message.to[i]) for i in range(0, len(message.to)) ]) else: email_message['To'] = ', '.join(message.to) # Add Reply-To if message.reply_to: email_message['Reply-To'] = message.reply_to # Add CC recipients to message header if message.cc: email_message['Cc'] = ', '.join(message.cc) # Add subject email_message['Subject'] = self._encodeHeader(message.subject) # Add date email_message['Date'] = message.date # Add JSON header if message.header.data: email_message['X-SMTPAPI'] = Header(message.header.as_json(), charset='8bit', maxlinelen=20480000) # Add custom headers headerError = False if message.headers: for k, v in message.headers.iteritems(): if isinstance(k, basestring) and isinstance( v, basestring) and self._isAscii(k): email_message[k] = self._encodeHeader(v) else: headerError = True break if headerError: raise ValueError('JSON in headers is valid but incompatible') # build a list of recipients (hide BCC recipients from header) recipients = email_message['To'].split(', ') if message.cc: recipients += message.cc if message.bcc: recipients += message.bcc # Add files if any if message.attachments: for attach in message.attachments: f = self._getFileMIME(attach) if f: email_message.attach(f) server = smtplib.SMTP(*self.HOSTPORT) if self.tls: server.starttls() try: server.login(self.username, self.password) server.sendmail(email_message['From'], recipients, email_message.as_string()) server.quit() except Exception, e: raise exceptions.SGServiceException(e)
class Http(object): """ Transport to send emails using http """ HOSTPORT = ('sendgrid.com', ) def __init__(self, username, password, **opts): """ Construct web transport object Args: username: Sendgrid username password: Sendgrid password ssl: Use SSL user: Send mail on behalf of this user """ self.username = username self.password = password self.ssl = opts.get('ssl', True) self.user = opts.get('user', None) def send(self, message): """ Send message Args: message: Sendgrid Message object Returns: True on success Raises: SGServiceException: on error """ protocol = "https://" if not self.ssl: protocol = "http://" endpoint = "/api/mail.send.json" url = protocol + ":".join(map(str, self.HOSTPORT)) + endpoint data = { 'api_user': self.username, 'api_key': self.password, 'to': message.to, 'subject': message.subject, 'from': message.from_address, 'date': message.date, } if message.header.data: data['x-smtpapi'] = message.header.as_json() if message.headers: data['headers'] = json.dumps(message.headers) if message.attachments: for attach in message.attachments: try: f = open(attach['file'], 'rb') data['files[' + attach['name'] + ']'] = f.read() f.close() except IOError: data['files[' + attach['name'] + ']'] = attach['file'] optional_params = { 'toname': message.to_name, 'text': message.text, 'html': message.html, 'cc': message.cc, # for future use, not yet implemented 'bcc': message.bcc, 'fromname': message.from_name, 'replyto': message.reply_to, 'user': self.user, } for key in optional_params: if optional_params[key]: data[key] = optional_params[key] data = urllib.urlencode(data, 1) req = urllib2.Request(url, data) try: f = urllib2.urlopen(req) output = f.read() except IOError, e: try: output = e.read() except AttributeError: raise exceptions.SGServiceException(e) output = json.loads(output) if output['message'] == 'error': raise exceptions.SGServiceException(output['errors'][0]) return True
def send(self, message): """ Send message Args: message: Sendgrid Message object Returns: True on success Raises: SGServiceException: on error """ protocol = "https://" if not self.ssl: protocol = "http://" endpoint = "/api/mail.send.json" url = protocol + ":".join(map(str, self.HOSTPORT)) + endpoint data = { 'api_user': self.username, 'api_key': self.password, 'to': message.to, 'subject': message.subject, 'from': message.from_address, 'date': message.date, } if message.header.data: data['x-smtpapi'] = message.header.as_json() if message.headers: data['headers'] = json.dumps(message.headers) if message.attachments: for attach in message.attachments: try: f = open(attach['file'], 'rb') data['files[' + attach['name'] + ']'] = f.read() f.close() except IOError: data['files[' + attach['name'] + ']'] = attach['file'] optional_params = { 'toname': message.to_name, 'text': message.text, 'html': message.html, 'cc': message.cc, # for future use, not yet implemented 'bcc': message.bcc, 'fromname': message.from_name, 'replyto': message.reply_to, 'user': self.user, } for key in optional_params: if optional_params[key]: data[key] = optional_params[key] data = urllib.urlencode(data, 1) req = urllib2.Request(url, data) try: f = urllib2.urlopen(req) output = f.read() except IOError, e: try: output = e.read() except AttributeError: raise exceptions.SGServiceException(e)
class Http(object): """ Transport to send emails using http """ def __init__(self, username, password, ssl=True): """ Construct web transport object Args: username: Sendgrid uaername password: Sendgrid password ssl: Use SSL """ self.username = username self.password = password self.ssl = ssl def send(self, message): """ Send message Args: message: Sendgrid Message object Returns: True on success Raises: SGServiceException: on error """ url = "https://sendgrid.com/api/mail.send.json" if not self.ssl: url = "http://sendgrid.com/api/mail.send.json" data = { 'api_user': self.username, 'api_key': self.password, 'to': message.to, 'subject': message.subject, 'from': message.from_address, 'date': message.date, } if message.header.data: data['x-smtpapi'] = message.header.as_json() if message.headers: data['headers'] = json.dumps(message.headers) if message.attachments: for attach in message.attachments: try: f = open(attach['file'], 'rb') data['files[' + attach['name'] + ']'] = f.read() f.close() except IOError: data['files[' + attach['name'] + ']'] = attach['file'] optional_params = { 'toname': message.to_name, 'text': message.text, 'html': message.html, 'bcc': message.bcc, 'fromname': message.from_name, 'replyto': message.reply_to, } for key in optional_params: if optional_params[key]: data[key] = optional_params[key] data = urllib.urlencode(data, 1) req = urllib2.Request(url, data) try: f = urllib2.urlopen(req) output = f.read() except IOError, e: output = e.read() output = json.loads(output) if output['message'] == 'error': raise exceptions.SGServiceException(output['errors']) return True