def send(self, message, envelope_from=None): assert message.send_to, "No recipients have been added" assert message.sender, ( "The message does not specify a sender and a default sender " "has not been configured") if message.has_bad_headers(): raise BadHeaderError if message.date is None: message.date = time.time() if not message.subject: message.subject = word("(no subject)") sgmessage = SGMail( from_email=Email(message.sender), to_emails=[ To(addressee) for addressee in sanitize_addresses(message.recipients) ], subject=message.subject, plain_text_content=message.body, html_content=message.html) if message.reply_to: sgmessage.reply_to = ReplyTo(message.reply_to) if message.cc: for recipient in list(sanitize_addresses(message.cc)): sgmessage.add_cc(recipient) if message.bcc: for recipient in list(sanitize_addresses(message.bcc)): sgmessage.add_bcc(recipient) if message.attachments: for flask_attachment in message.attachments: attachment = Attachment() attachment.file_content = FileContent( base64.b64encode(flask_attachment.data).decode()) attachment.file_type = FileType(flask_attachment.content_type) attachment.file_name = FileName(flask_attachment.filename) attachment.disposition = Disposition( flask_attachment.disposition) sgmessage.add_attachment(attachment) sg = SendGridAPIClient(self.mail.api_key) response = sg.send(sgmessage) if response.status_code >= 400: sys.stderr.write("SendGrid status code: " + str(response.status_code) + "\n") sys.stderr.write("SendGrid response headers: " + repr(response.headers) + "\n") try: sys.stderr.write(repr(response.body) + "\n") except: pass raise Exception("Failed to send e-mail message to SendGrid") email_dispatched.send(message, app=current_app._get_current_object())
def send(self, message, envelope_from=None): assert message.send_to, "No recipients have been added" assert message.sender, ( "The message does not specify a sender and a default sender " "has not been configured") if message.has_bad_headers(): raise BadHeaderError if message.date is None: message.date = time.time() data = {'to': ', '.join(list(sanitize_addresses(message.send_to)))} if hasattr(message, 'mailgun_variables') and isinstance( message.mailgun_variables, dict): for key, val in message.mailgun_variables.items(): data['v:' + str(key)] = val response = requests.post( self.mail.api_url, auth=HTTPBasicAuth('api', self.mail.api_key), data=data, files={'message': ('mime_message', message.as_string())}) if response.status_code >= 400: sys.stderr.write("SendGrid status code: " + str(response.status_code) + "\n") sys.stderr.write("SendGrid response headers: " + repr(response.headers) + "\n") try: sys.stderr.write(repr(response.body) + "\n") except: pass raise Exception("Failed to send e-mail message to " + self.mail.api_url) email_dispatched.send(message, app=current_app._get_current_object())
def send_mail_task(msg): send_to = list(sanitize_addresses(msg.send_to)) part = MIMEText(msg.html, 'html') mp = MIMEMultipart('alternative') mp['Subject'] = msg.subject mp['From'] = FROM_USER mp['To'] = ','.join(send_to) mp.attach(part) s = smtplib.SMTP_SSL("smtp.qq.com", port=465) s.login(FROM_USER, EXMAIL_PASSWORD) s.sendmail(FROM_USER, send_to, bytes(mp.as_string(), 'utf-8')) s.quit()
def send_mail(msg): send_to = list(sanitize_addresses(msg.send_to)) part = MIMEText(msg.html, "html") mp = MIMEMultipart("alternative") mp["Subject"] = msg.subject mp["From"] = FROM_USER mp["To"] = ",".join(send_to) mp.attach(part) s = smtplib.SMTP("smtp.qq.com", port=587) s.set_debuglevel(True) s.starttls() s.login(FROM_USER, EXMAIL_PASSWORD) s.sendmail(FROM_USER, send_to, mp.as_bytes()) s.quit()
def send(self, message, envelope_from=None): assert message.send_to, "No recipients have been added" assert message.sender, ( "The message does not specify a sender and a default sender " "has not been configured") if message.has_bad_headers(): raise BadHeaderError if message.date is None: message.date = time.time() response = requests.post(self.mail.api_url, auth=HTTPBasicAuth('api', self.mail.api_key), data={'to': ', '.join(list(sanitize_addresses(message.send_to)))}, files={'message': ('mime_message', message.as_string())}) if response.status_code >= 400: raise Exception("Failed to send e-mail message to " + self.mail.api_url) email_dispatched.send(message, app=current_app._get_current_object())
def send_mail_task(msg): send_to = list(sanitize_addresses(msg.send_to)) part = MIMEText(_text=msg.html, _subtype='html') mp = MIMEMultipart('alternative') mp['Subject'] = msg.subject mp['From'] = '*****@*****.**' mp['To'] = ','.join(send_to) mp.attach(part) s = smtplib.SMTP_SSL(host=MAIL_SERVER, port=int(MAIL_PORT)) s.login(MAIL_USERNAME, MAIL_PASSWORD) s.sendmail(from_addr=MAIL_USERNAME, to_addrs=send_to, msg=bytes(mp.as_string(), 'utf-8')) s.quit()
def _message(self): """Creates email as 'multipart/related' instead of 'multipart/mixed'""" ascii_attachments = current_app.extensions['mail'].ascii_attachments encoding = self.charset or 'utf-8' attachments = self.attachments or [] if len(attachments) == 0 and not self.html: # No html content and zero attachments means plain text msg = self._mimetext(self.body) elif len(attachments) > 0 and not self.html: # No html and at least one attachment means multipart msg = MIMEMultipart() msg.attach(self._mimetext(self.body)) else: # Anything else msg = MIMEMultipart( 'related') # This fixes embedded images in the html body alternative = MIMEMultipart('alternative') alternative.attach(self._mimetext(self.body, 'plain')) alternative.attach(self._mimetext(self.html, 'html')) msg.attach(alternative) if self.subject: msg['Subject'] = sanitize_subject(force_text(self.subject), encoding) msg['From'] = sanitize_address(self.sender, encoding) msg['To'] = ', '.join( list(set(sanitize_addresses(self.recipients, encoding)))) msg['Date'] = formatdate(self.date, localtime=True) # see RFC 5322 section 3.6.4. msg['Message-ID'] = self.msgId if self.cc: msg['Cc'] = ', '.join( list(set(sanitize_addresses(self.cc, encoding)))) if self.reply_to: msg['Reply-To'] = sanitize_address(self.reply_to, encoding) if self.extra_headers: for k, v in self.extra_headers.items(): msg[k] = v SPACES = re.compile(r'[\s]+', re.UNICODE) for attachment in attachments: f = MIMEBase(*attachment.content_type.split('/')) f.set_payload(attachment.data) encode_base64(f) filename = attachment.filename if filename and ascii_attachments: # force filename to ascii filename = unicodedata.normalize('NFKD', filename) filename = filename.encode('ascii', 'ignore').decode('ascii') filename = SPACES.sub(u' ', filename).strip() try: filename and filename.encode('ascii') except UnicodeEncodeError: filename = ('UTF8', '', filename) f.add_header('Content-Disposition', attachment.disposition, filename=filename) for key, value in attachment.headers: f.add_header(key, value) msg.attach(f) if message_policy: msg.policy = message_policy return msg