Send an email with html content, eg:
    send_email_smtp(
        'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
768679
def send_email_smtp(to, subject, html_content, config,
                    files=None, data=None, images=None, dryrun=False,
                    cc=None, bcc=None, mime_subtype='mixed'):
    
    smtp_mail_from = config.get('SMTP_MAIL_FROM')
    to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg['Subject'] = subject
    msg['From'] = smtp_mail_from
    msg['To'] = ', '.join(to)
    msg.preamble = 'This is a multi-part message in MIME format.'

    recipients = to
    if cc:
        cc = get_email_address_list(cc)
        msg['CC'] = ', '.join(cc)
        recipients = recipients + cc

    if bcc:
        # don't add bcc in header
        bcc = get_email_address_list(bcc)
        recipients = recipients + bcc

    msg['Date'] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, 'html')
    msg.attach(mime_text)

    # Attach files by reading them from disk
    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, 'rb') as f:
            msg.attach(
                MIMEApplication(
                    f.read(),
                    Content_Disposition="attachment; filename='%s'" % basename,
                    Name=basename))

    # Attach any files passed directly
    for name, body in (data or {}).items():
        msg.attach(
            MIMEApplication(
                body,
                Content_Disposition="attachment; filename='%s'" % name,
                Name=name,
            ))

    # Attach any inline images, which may be required for display in
    # HTML content (inline)
    for msgid, body in (images or {}).items():
        image = MIMEImage(body)
        image.add_header('Content-ID', '<%s>' % msgid)
        image.add_header('Content-Disposition', 'inline')
        msg.attach(image)

    send_MIME_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
208338
def send_smtp(mail)
      smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT)
      smtp.enable_starttls_auto
      secret = {
        :consumer_key => SMTP_CONSUMER_KEY, 
        :consumer_secret => SMTP_CONSUMER_SECRET,
        :token => @email_credentials[:smtp_oauth_token],
        :token_secret => @email_credentials[:smtp_oauth_token_secret]
      }
      smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session|
        print "Sending message..."
        session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations)
        puts ".sent!"
      end
    end
99910
def _send(self, email_message):
        """"""
        if not email_message.recipients():
            return False

        if set(email_message.recipients()).issubset(admin_emails()):
            # Skip on admin notifications
            return super(DevEmailBackend, self)._send(email_message)

        from_email = sanitize_address(email_message.from_email, email_message.encoding)
        try:
            recipients = [sanitize_address(addr, email_message.encoding)
                          for addr in settings.DEV_EMAIL_LIST]
        except:
            raise ImproperlyConfigured("You must set a DEV_EMAIL_LIST setting to use the Dev Email Backend.")

        message = email_message.message()
        charset = message.get_charset().get_output_charset() if message.get_charset() else "utf-8"
        try:
            self.connection.sendmail(from_email, recipients,
                                     force_bytes(message.as_string(), charset))
        except:
            if not self.fail_silently:
                raise
            return False
        return True
1263367
def send_email(self, to, subject, content, files=None):
        
        msg = EmailSender._construct_msg(self, to, subject, content, files=files)
        try:
            self.smtp.sendmail(self.from_, to, str(msg))
        except:
            self.login()
            self.smtp.sendmail(self.from_, to, str(msg))
679657
def main() -> None:
    
    logging.basicConfig()
    log.setLevel(logging.DEBUG)
    parser = argparse.ArgumentParser(
        description="Send an e-mail from the command line.")
    parser.add_argument("sender", action="store",
                        help="Sender's e-mail address")
    parser.add_argument("host", action="store",
                        help="SMTP server hostname")
    parser.add_argument("user", action="store",
                        help="SMTP username")
    parser.add_argument("password", action="store",
                        help="SMTP password")
    parser.add_argument("recipient", action="append",
                        help="Recipient e-mail address(es)")
    parser.add_argument("subject", action="store",
                        help="Message subject")
    parser.add_argument("body", action="store",
                        help="Message body")
    parser.add_argument("--attach", nargs="*",
                        help="Filename(s) to attach")
    parser.add_argument("--tls", action="store_false",
                        help="Use TLS connection security")
    parser.add_argument("--verbose", action="store_true",
                        help="Be verbose")
    parser.add_argument("-h --help", action="help",
                        help="Prints this help")
    args = parser.parse_args()
    (result, msg) = send_email(
        from_addr=args.sender,
        to=args.recipient,
        subject=args.subject,
        body=args.body,
        host=args.host,
        user=args.user,
        password=args.password,
        use_tls=args.tls,
        attachment_filenames=args.attach,
        verbose=args.verbose,
    )
    if result:
        log.info("Success")
    else:
        log.info("Failure")
        # log.error(msg)
    sys.exit(0 if result else 1)
374011
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
    # check if closed!!!!!! XXX
    
    if isinstance(contents, text_type):
        contents = [contents]
    if isinstance(attachments, text_type):
        attachments = [attachments]

    # merge contents and attachments for now.
    if attachments is not None:
        for a in attachments:
            if not os.path.isfile(a):
                raise TypeError("'{0}' is not a valid filepath".format(a))
        contents = attachments if contents is None else contents + attachments

    has_included_images, content_objects = prepare_contents(contents, encoding)
    msg = MIMEMultipart()
    if headers is not None:
        # Strangely, msg does not have an update method, so then manually.
        for k, v in headers.items():
            msg[k] = v
    if headers is None or "Date" not in headers:
        msg["Date"] = formatdate()

    msg_alternative = MIMEMultipart("alternative")
    msg_related = MIMEMultipart("related")
    msg_related.attach("-- HTML goes here --")
    msg.attach(msg_alternative)
    add_subject(msg, subject)
    add_recipients_headers(user, useralias, msg, addresses)
    htmlstr = ""
    altstr = []
    if has_included_images:
        msg.preamble = "This message is best displayed using a MIME capable email reader."

    if contents is not None:
        for content_object, content_string in zip(content_objects, contents):
            if content_object["main_type"] == "image":
                # all image objects need base64 encoding, so do it now
                email.encoders.encode_base64(content_object["mime_object"])
                # aliased image {'path' : 'alias'}
                if isinstance(content_string, dict) and len(content_string) == 1:
                    for key in content_string:
                        hashed_ref = str(abs(hash(key)))
                        alias = content_string[key]
                    # pylint: disable=undefined-loop-variable
                    content_string = key
                else:
                    alias = os.path.basename(str(content_string))
                    hashed_ref = str(abs(hash(alias)))

                # TODO: I should probably remove inline now that there is "attachments"
                # if string is `inline`, inline, else, attach
                # pylint: disable=unidiomatic-typecheck
                if type(content_string) == inline:
                    htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
                    content_object["mime_object"].add_header(
                        "Content-ID", "<{0}>".format(hashed_ref)
                    )
                    altstr.append("-- img {0} should be here -- ".format(alias))
                    # inline images should be in related MIME block
                    msg_related.attach(content_object["mime_object"])
                else:
                    # non-inline images get attached like any other attachment
                    msg.attach(content_object["mime_object"])

            else:
                if content_object["encoding"] == "base64":
                    email.encoders.encode_base64(content_object["mime_object"])
                    msg.attach(content_object["mime_object"])
                elif content_object["sub_type"] not in ["html", "plain"]:
                    msg.attach(content_object["mime_object"])
                else:
                    if newline_to_break:
                        content_string = content_string.replace("\n", "<br>")
                    try:
                        htmlstr += "<div>{0}</div>".format(content_string)
                    except UnicodeEncodeError:
                        htmlstr += u"<div>{0}</div>".format(content_string)
                    altstr.append(content_string)

    msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
    msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
    msg_alternative.attach(msg_related)
    return msg
394808
def add_to_emails(self, *emails):
        
        assert all(isinstance(element, (str, unicode)) for element in emails), emails
        post_parameters = emails
        headers, data = self._requester.requestJsonAndCheck(
            "POST",
            "/user/emails",
            input=post_parameters
        )
561052
function(to,tmpName,obj,cb){
    fs.readFile(
      path.join(__dirname, 'emailBoiler.html'),
      'utf8',
      function(err, data) {
        if (err){
          return cb(err);
        }
        var tmp = cfg.templates[tmpName];
        var locals = {
          title: '',
          content: tmp.text,
        };

        var html = ejs.render(data, locals);
        obj.link = '<a href="' + obj.url + '">' + tmp.linkText + '</a>';
        html = ejs.render(html,obj);

        var subject = ejs.render(tmp.subject,obj);

        sendEmail(to,subject,html,cb);
      }
    );
  }
633373
def send(self, text, fmt):
        
        main_fmt, sub_fmt = fmt.split('/')
        if sub_fmt.lower() == "text":
            msg = MIMEText(text, "plain")
        elif sub_fmt.lower() == "html":
            msg = MIMEText(text, "html")
        else:
            raise ValueError("Unknown message format: {}".format(fmt))
        msg['Subject'] = self._subject
        msg['From'] = self._sender
        msg['To'] = ', '.join(self._recipients)
        if self._port is None:
            conn_kwargs = dict(host=self._server)
        else:
            conn_kwargs = dict(host=self._server, port=self._port)
        self._log.info("connect to email server {}".format(conn_kwargs))
        try:
            s = smtplib.SMTP(**conn_kwargs)
            #s.set_debuglevel(2)
            refused = s.sendmail(self._sender, self._recipients, msg.as_string())
            if refused:
                self._log.warn("Email to {:d} recipients was refused".format(len(refused)))
                for person, (code, msg) in refused.items():
                    self._log("Email to {p} was refused ({c}): {m}".format(p=person, c=code, m=msg))
            s.quit()
            n_recip = len(self._recipients)
        except Exception as err:
            self._log.error("connection to SMTP server failed: {}".format(err))
            n_recip = 0
        return n_recip
409859
def set_email(self, email, _vars=None, lists=None, templates=None, verified=0, optout=None, send=None, send_vars=None):
        
        _vars = _vars or {}
        lists = lists or []
        templates = templates or []
        send_vars = send_vars or []
        data = {'email': email,
                'vars':  _vars.copy(),
                'lists': lists,
                'templates': templates,
                'verified': int(verified)}
        if optout is not None:
            data['optout'] = optout
        if send is not None:
            data['send'] = send
        if send_vars:
            data['send_vars'] = send_vars
        return self.api_post('email', data)
538051
def dump_emails(part):
    """"""

    print("Sent emails:")
    for email in mail.outbox:
        print(getattr(email, part))
791196
public function previewContentWithHTML($content_html, $email) {
        $data = [ ];
        $data['content_html'] = $content_html;
        $data['email'] = $email;

        $result = $this->apiPost('preview', $data);
        return $result;
    }
575007
def render_sendmail(self):
        
        phase = 'exit_plugins'
        plugin = 'sendmail'
        if not self.dj.dock_json_has_plugin_conf(phase, plugin):
            return

        if self.spec.smtp_host.value and self.spec.smtp_from.value:
            self.dj.dock_json_set_arg(phase, plugin, 'url',
                                      self.spec.builder_openshift_url.value)
            self.dj.dock_json_set_arg(phase, plugin, 'smtp_host',
                                      self.spec.smtp_host.value)
            self.dj.dock_json_set_arg(phase, plugin, 'from_address',
                                      self.spec.smtp_from.value)
        else:
            logger.info("removing sendmail from request, "
                        "requires smtp_host and smtp_from")
            self.dj.remove_plugin(phase, plugin)
            return

        if self.spec.kojihub.value and self.spec.kojiroot.value:
            self.dj.dock_json_set_arg(phase, plugin,
                                      'koji_hub', self.spec.kojihub.value)
            self.dj.dock_json_set_arg(phase, plugin,
                                      "koji_root", self.spec.kojiroot.value)

            if self.spec.smtp_to_submitter.value:
                self.dj.dock_json_set_arg(phase, plugin, 'to_koji_submitter',
                                          self.spec.smtp_to_submitter.value)
            if self.spec.smtp_to_pkgowner.value:
                self.dj.dock_json_set_arg(phase, plugin, 'to_koji_pkgowner',
                                          self.spec.smtp_to_pkgowner.value)

        if self.spec.smtp_additional_addresses.value:
            self.dj.dock_json_set_arg(phase, plugin, 'additional_addresses',
                                      self.spec.smtp_additional_addresses.value)

        if self.spec.smtp_error_addresses.value:
            self.dj.dock_json_set_arg(phase, plugin,
                                      'error_addresses', self.spec.smtp_error_addresses.value)

        if self.spec.smtp_email_domain.value:
            self.dj.dock_json_set_arg(phase, plugin,
                                      'email_domain', self.spec.smtp_email_domain.value)
599000
public boolean sendHtmlEmail(String toEmail, String subject, String content) {

        //
        // 这个类主要是设置邮件
        //
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost(emailProperties.getEmailHost());
        mailInfo.setMailServerPort(emailProperties.getEmailPort());
        mailInfo.setValidate(true);
        mailInfo.setUserName(emailProperties.getEmailUser());
        mailInfo.setPassword(emailProperties.getEmailPassword());// 您的邮箱密码

        mailInfo.setFromAddress(emailProperties.getFromEmail());
        mailInfo.setToAddress(toEmail);

        mailInfo.setSubject(subject);
        mailInfo.setContent(content);

        // 这个类主要来发送邮件
        return SimpleMailSender.sendHtmlMail(mailInfo);// 发送文体格式
    }
968363
def main():
    
    log = logging.getLogger(mod_logger + '.main')
    parser = argparse.ArgumentParser(description='This module allows sending email messages.')
    parser.add_argument('-f', '--file', help='Full path to a plain text file', required=False)
    parser.add_argument('-s', '--sender', help='Email address of the sender', required=False)
    parser.add_argument('-r', '--recipient', help='Email address of the recipient', required=False)
    args = parser.parse_args()

    am = AssetMailer()
    err = None
    if args.file:
        try:
            am.send_text_file(text_file=args.file, sender=args.sender, recipient=args.recipient)
        except AssetMailerError:
            _, ex, trace = sys.exc_info()
            err = '{n}: There was a problem sending email with file {f} from sender {s} to recipient {r}:\n{e}'.format(
                n=ex.__class__.__name__, f=args.file, s=args.sender, r=args.recipient, e=str(ex))
            log.error(err)
    else:
        try:
            am.send_cons3rt_agent_logs()
        except AssetMailerError:
            _, ex, trace = sys.exc_info()
            err = '{n}: There was a problem sending cons3rt agent log files:\n{e}'.format(
                n=ex.__class__.__name__, e=str(ex))
            log.error(err)
    if err is None:
        log.info('Successfully send email')
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()
763525
def send(self, *args, **kwargs):
        """"""
        conn = SMTP(*args, **kwargs)
        send_result = conn.send(self)
        return conn, send_result