Actually sends the mail with `subject` and `body` and optionanl log_file attachements
        to all members of `receivers_list`.
509288
def _send_mail(self, receivers_list, subject, body, log_files=None):
        if not receivers_list:
            self.log.info('no valid addresses in requested addresses. Doing nothing')
            return

        self.log.info('sending notification to %s ...', receivers_list)

        """"""
        if log_files:
            msg = MIMEMultipart()
            msg.attach(MIMEText(body))
            for entry in log_files:
                log_mime = MIMEBase('application', "octet-stream")
                log_file = entry[0]  # Output.file
                log_file.seek(0)
                log_mime.set_payload(log_file.read())
                encoders.encode_base64(log_mime)
                log_mime.add_header('Content-Disposition',
                                    'attachment; filename="{}"'.format(entry[1]['filename']))
                msg.attach(log_mime)
        else:
            msg = MIMEText(body)
        msg['Subject'] = subject
        msg['From'] = self.from_address
        msg['To'] = ', '.join([x.strip() for x in receivers_list])

        s = None
        try:
            s = get_smtp_session(self.workflow, self.smtp_fallback)
            s.sendmail(self.from_address, receivers_list, msg.as_string())
        except (socket.gaierror, smtplib.SMTPException):
            self.log.error('Error communicating with SMTP server')
            raise
        finally:
            if s is not None:
                s.quit()
1047157
def send_mail(subject, message, recipient_list, from_email=None,
              fail_silently=False, auth_user=None, auth_password=None,
              connection=None, **kwargs):
    
    connection = connection or get_connection(
        username=auth_user,
        password=auth_password,
        fail_silently=fail_silently,
    )
    mail_message = EmailMessage(subject, message, from_email, recipient_list,
                                **kwargs)

    return connection.send_messages([mail_message])
374203
public function send($subject, array $options = array()) {
        $to = $this->to;
        $from = $this->from;
        $cc = $this->cc;
        $bcc = $this->bcc;
        $replyTo = $this->replyTo;

        foreach ($options as $key => $value) {
            $$key = $value;
        }

        $this->createHeaders($from, $cc, $bcc, $replyTo);

        if (!empty($this->html)) {
            $message = $this->html;

            $endWithSeparator = false;
            if ($this->text || $this->attachments) {
                $this->headers("Content-type: multipart/" . (($this->attachments) ? 'mixed' : 'alternative') . "; charset=" . $this->htmlCharset);
                $endWithSeparator = true;
            }
            else {
                $this->headers("Content-type: text/html; charset=" . $this->htmlCharset);
                $this->headers('Content-Transfer-Encoding:8bit');
            }
            $this->headers("MIME-Version: 1.0");

            if (!empty($this->text)) {
                $this->separateHeaders();
                $this->headers("Content-type: text/plain; charset=" . $this->htmlCharset);
                $this->headers('Content-Transfer-Encoding:8bit');
                $this->headers($this->text);

                $this->separateHeaders();
                $this->headers("Content-type: text/html; charset=" . $this->htmlCharset);
                $this->headers('Content-Transfer-Encoding:8bit');
                $this->headers($message);
            }
        }
        elseif (!empty($this->text)) {
            $message = $this->text;
        }
        else {
            throw new Exception('Email content not set! Use either/both of setText() and setHTML()');
        }

        if (!empty($this->attachments)) {
            $this->setAttachmentHeader();
        }

        if ($endWithSeparator)
            $this->separateHeaders();

        return mail($to, $subject, $message, $this->headers);
    }
137961
def send_message(body, options = {})
      logger.debug "Sending message: #{body}"
      client.send_message id, domain, body, options
    end
965787
def send_mail(self, subject, to, template, **template_ctx):
        
        if not self.mail:
            from warnings import warn
            warn('Attempting to send mail without the mail bundle installed! '
                 'Please install it, or fix your configuration.')
            return

        self.mail.send(subject, to, template, **dict(
            **self.security.run_ctx_processor('mail'),
            **template_ctx))
1089962
def send_mail_template(subject, template, addr_from, addr_to, context=None,
                       attachments=None, fail_silently=None, addr_bcc=None,
                       headers=None):
    
    if context is None:
        context = {}
    if attachments is None:
        attachments = []
    if fail_silently is None:
        fail_silently = settings.EMAIL_FAIL_SILENTLY
    # Add template accessible settings from yacms to the context
    # (normally added by a context processor for HTTP requests).
    context.update(context_settings())
    # Allow for a single address to be passed in.
    # Python 3 strings have an __iter__ method, so the following hack
    # doesn't work: if not hasattr(addr_to, "__iter__"):
    if isinstance(addr_to, str) or isinstance(addr_to, bytes):
        addr_to = [addr_to]
    if addr_bcc is not None and (isinstance(addr_bcc, str) or
                                 isinstance(addr_bcc, bytes)):
        addr_bcc = [addr_bcc]
    # Loads a template passing in vars as context.
    render = lambda type: loader.get_template("%s.%s" %
                          (template, type)).render(Context(context))
    # Create and send email.
    msg = EmailMultiAlternatives(subject, render("txt"),
                                 addr_from, addr_to, addr_bcc,
                                 headers=headers)
    msg.attach_alternative(render("html"), "text/html")
    for attachment in attachments:
        msg.attach(*attachment)
    msg.send(fail_silently=fail_silently)
99605
def send_mass_template_mail(subject_template, body_template, recipients, context=None):
    
    if context:
        subject, body = render_mail_template(subject_template, body_template, context)
    else:
        subject, body = subject_template, body_template

    message_tuples = [(subject, body, conf.get('DEFAULT_FROM_EMAIL'), [r]) for r in recipients]

    send_mass_mail(message_tuples)
1081320
public void sendMailWithAttachment (String to, String subject, String content, String filename) throws MessagingException{
        Properties props = new Properties();
        props.put("mail.smtp.user", emailConfg.getUser());
        props.put("mail.smtp.host", emailConfg.getHost());
        props.put("mail.smtp.port", emailConfg.getPort());
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.debug", emailConfg.getDebug());
        props.put("mail.smtp.auth", emailConfg.getAuth());
        props.put("mail.smtp.ssl.trust", emailConfg.host);

        SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), (String)secret.get(SecretConstants.EMAIL_PASSWORD));
        Session session = Session.getInstance(props, auth);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(emailConfg.getUser()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
    }
682359
def send(self):
        
        # if it has already been sent don't send again
        if self.status is OUTWARD_STATUS.get('sent'):
            return False
        # determine recipients
        recipients = self.get_recipients()
        # init empty list that will contain django's email objects
        emails = []

        # prepare text plain if necessary
        if OUTWARD_HTML:
            # store plain text in var
            html_content = self.message
            # set EmailClass to EmailMultiAlternatives
            EmailClass = EmailMultiAlternatives
        else:
            EmailClass = EmailMessage

        # default message is plain text
        message = strip_tags(self.message)

        # loop over recipients and fill "emails" list
        for recipient in recipients:
            msg = EmailClass(
                # subject
                self.subject,
                # message
                message,
                # from
                settings.DEFAULT_FROM_EMAIL,
                # to
                [recipient],
            )
            if OUTWARD_HTML:
                msg.attach_alternative(html_content, "text/html")
            # prepare email object
            emails.append(msg)

        # try sending email
        try:
            # counter will count how many emails have been sent
            counter = 0
            for email in emails:
                # if step reached
                if counter == OUTWARD_STEP:
                    # reset counter
                    counter = 0
                    # sleep
                    time.sleep(OUTWARD_DELAY)
                # send email
                email.send()
                # increase counter
                counter += 1
        # if error (connection refused, SMTP down)
        except socket.error as e:
            # log the error
            from logging import error
            error('nodeshot.core.mailing.models.outward.send(): %s' % e)
            # set status of the instance as "error"
            self.status = OUTWARD_STATUS.get('error')
        # change status
        self.status = OUTWARD_STATUS.get('sent')
        # save
        self.save()
586435
def do_send_mail(self, is_ssl, mail_to_list, subject, content, file_name_list):
        
        if is_ssl:
            smtp = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
        else:
            smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
        smtp.ehlo(name='foxmail')
        # 调用login时，如果没有调用过 echlo 会自动调用该方法，但是默认使用的name为计算机名
        # 如果计算机名有中文，就会返回503方法未实现的异常
        smtp.login(self.mail_from, self.password)
        msg = MIMEMultipart()
        msg['From'] = self.mail_from
        msg['To'] = ', '.join(mail_to_list)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        # 如果 content 是 html，则需要设置 _subtype='html'
        # 默认情况下 _subtype='plain'，即纯文本
        msg.attach(MIMEText(content, _charset='utf-8'))
        for fn in file_name_list:
            part = MIMEText(open(fn, 'rb').read(), 'base64', 'utf-8')
            part["Content-Type"] = 'application/octet-stream'
            basename = os.path.basename(fn)
            if PY2:
                basename = basename.encode('gb2312')
            # 文件名使用 gb2312 编码，否则会没有附件
            part.add_header('Content-Disposition', 'attachment', filename=('gb2312', '', basename))
            msg.attach(part)
        smtp.sendmail(self.mail_from, mail_to_list, msg.as_string())
        smtp.close()
893551
async def send_mail(
        self, sender, recipients, message, mail_options=None, rcpt_options=None
    ):
        
        return await self.sendmail(
            sender, recipients, message, mail_options, rcpt_options
        )
391828
public void sendWithAttachment(String subject, 
                                 String textBody,
                                 String attachmentType,
                                 String attachmentName,
                                 InputStream is)
  {
    try {
      MimeMessage msg = new MimeMessage(getSession());

      if(_from.length > 0)
        msg.addFrom(_from);
      msg.addRecipients(RecipientType.TO, _to);
      if(subject != null)
        msg.setSubject(subject);
      
      // msg.setContent(textBody, "multipart/mime");
      
      MimeMultipart multipart = new MimeMultipart();
      
      MimeBodyPart textBodyPart = new MimeBodyPart();
      textBodyPart.setText(textBody);
      multipart.addBodyPart(textBodyPart);
      
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      TempBuffer tb = TempBuffer.create();
      byte []buffer = tb.buffer();
      int len;
      
      while ((len = is.read(buffer, 0, buffer.length)) >= 0) {
        bos.write(buffer, 0, len);
      }
      bos.close();
      byte []content = bos.toByteArray();
      TempBuffer.free(tb);
      
      DataSource dataSource
        = new ByteArrayDataSource(content, attachmentType);
      
      MimeBodyPart pdfBodyPart = new MimeBodyPart();
      pdfBodyPart.setDataHandler(new DataHandler(dataSource));
      pdfBodyPart.setFileName(attachmentName);
      multipart.addBodyPart(pdfBodyPart);
      
      msg.setContent(multipart);

      send(msg);
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
664057
def _sendFiles(
        self, files, message=None, thread_id=None, thread_type=ThreadType.USER
    ):
        
        thread_id, thread_type = self._getThread(thread_id, thread_type)
        data = self._getSendData(
            message=self._oldMessage(message),
            thread_id=thread_id,
            thread_type=thread_type,
        )

        data["action_type"] = "ma-type:user-generated-message"
        data["has_attachment"] = True

        for i, (file_id, mimetype) in enumerate(files):
            data["{}s[{}]".format(mimetype_to_key(mimetype), i)] = file_id

        return self._doSendRequest(data)
738300
public function send()
    {
        $this->logger->debug(
            'Attempting to send an email',
            $this->to()
        );

        $mail = $this->phpMailer;

        try {
            $this->setSmtpOptions($mail);

            $mail->CharSet = 'UTF-8';

            // Setting reply-to field, if required.
            $replyTo = $this->replyTo();
            if ($replyTo) {
                $replyArr = $this->emailToArray($replyTo);
                $mail->addReplyTo($replyArr['email'], $replyArr['name']);
            }

            // Setting from (sender) field.
            $from = $this->from();
            $fromArr = $this->emailToArray($from);
            $mail->setFrom($fromArr['email'], $fromArr['name']);

            // Setting to (recipients) field(s).
            $to = $this->to();
            foreach ($to as $recipient) {
                $toArr = $this->emailToArray($recipient);
                $mail->addAddress($toArr['email'], $toArr['name']);
            }

            // Setting cc (carbon-copy) field(s).
            $cc = $this->cc();
            foreach ($cc as $ccRecipient) {
                $ccArr = $this->emailToArray($ccRecipient);
                $mail->addCC($ccArr['email'], $ccArr['name']);
            }

            // Setting bcc (black-carbon-copy) field(s).
            $bcc = $this->bcc();
            foreach ($bcc as $bccRecipient) {
                $bccArr = $this->emailToArray($bccRecipient);
                $mail->addBCC($bccArr['email'], $bccArr['name']);
            }

            // Setting attachment(s), if required.
            $attachments = $this->attachments();
            foreach ($attachments as $att) {
                $mail->addAttachment($att);
            }

            $mail->isHTML(true);

            $mail->Subject = $this->subject();
            $mail->Body    = $this->msgHtml();
            $mail->AltBody = $this->msgTxt();

            $ret = $mail->send();

            $this->logSend($ret, $mail);

            return $ret;
        } catch (Exception $e) {
            $this->logger->error(
                sprintf('Error sending email: %s', $e->getMessage())
            );
        }
    }
498550
def send_message(template_id, to, reply_to, from, subject, merge_fields = nil, view_online = false,
                                            click_tracking = true, suppress_address = false, attachments = nil, headers = nil)
      if attachments
          upload(template_id, to, reply_to, from, subject, merge_fields, view_online, click_tracking,
                                                                                    suppress_address, attachments, headers, nil, nil)
        else
          post @endpoint, params = {template_id: template_id, to: to, reply_to: reply_to, from: from,
                                    subject: subject, merge_fields: merge_fields, view_online: view_online,
                                    click_tracking: click_tracking, suppress_address: suppress_address, headers: headers}
      end
    end
1067465
def email_user(
        self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs
    ):
        
        receiver = self.email
        if settings.EMAIL_OVERRIDE_ADDRESS:
            receiver = settings.EMAIL_OVERRIDE_ADDRESS

        send_mail(subject, message, from_email, [receiver], **kwargs)
993867
def send_mail(subject, message_plain, message_html, email_from, email_to,
              custom_headers={}, attachments=()):
    
    if not message_plain and not message_html:
        raise ValueError(_("Either message_plain or message_html should be not None"))

    if not message_plain:
        message_plain = html2text(message_html)

    message = {}

    message['subject'] = subject
    message['body'] = message_plain
    message['from_email'] = email_from
    message['to'] = email_to
    if attachments:
        message['attachments'] = attachments
    if custom_headers:
        message['headers'] = custom_headers

    msg = EmailMultiAlternatives(**message)
    if message_html:
        msg.attach_alternative(message_html, "text/html")
    msg.send()