Send SMTP template - terminal mailing part
488432
def deliver(template, from, to, vars={}, opts={})
      @info = vars
      @info[:company] = from[:name]

      mail(
        from: format_sender(from),
        to: to[:email],
        subject: humanize(template),
        template_path: 'system_notifications',
        template_name: template
      )
    end
339185
def main():
    
    description = 'Letter - a commandline interface'
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--gmail', action='store_true', help='Send via Gmail', )
    args = parser.parse_args()

    to       = raw_input('To address > ')
    subject  = raw_input('Subject > ')
    body     = raw_input('Your Message > ')


    if args.gmail:
        user = fromaddr = raw_input('Gmail Address > ')
        pw   = getpass.getpass()
        postie = letter.GmailPostman(user=user, pw=pw)
    else:
        postie = letter.Postman() # Unauthorized SMTP, localhost:25
        fromaddr = raw_input('From address > ')

    class Message(letter.Letter):
        Postie     = postie

        From       = fromaddr
        To         = to
        Subject    = subject
        Body       = body

    return 0
1261589
public static void setHost(MailHost mailHost) {
        switch (mailHost) {
            case NE163:
                host = "smtp.163.com";
                break;
            case GMAIL:
                host = "smtp.gmail.com";
                break;
            case SINA:
                host = "smtp.sina.com";
                break;
            case OUTLOOK:
                host = "smtp-mail.outlook.com";
                break;
            default:
                host = "smtp.qq.com";
                break;
        }
    }
55948
def send(self):
        
        if self.content_type.name == 'node':
            to = [self.to.user.email]
        elif self.content_type.name == 'layer':
            to = [self.to.email]
            # layer case is slightly special, mantainers need to be notified as well
            # TODO: consider making the mantainers able to switch off notifications
            for mantainer in self.to.mantainers.all().only('email'):
                to += [mantainer.email]
        else:
            to = [self.to.email]

        context = {
            'sender_name': self.from_name,
            'sender_email': self.from_email,
            'message': self.message,
            'site': settings.SITE_NAME,
            'object_type': self.content_type.name,
            'object_name': str(self.to)
        }
        message = render_to_string('mailing/inward_message.txt', context)

        email = EmailMessage(
            # subject
            _('Contact request from %(sender_name)s - %(site)s') % context,
            # message
            message,
            # from
            settings.DEFAULT_FROM_EMAIL,
            # to
            to,
            # reply-to header
            headers={'Reply-To': self.from_email}
        )

        import socket
        # try sending email
        try:
            email.send()
            self.status = 1
        # if error
        except socket.error as e:
            # log the error
            import logging
            log = logging.getLogger(__name__)
            error_msg = 'nodeshot.community.mailing.models.inward.send(): %s' % e
            log.error(error_msg)
            # set status of the instance as "error"
            self.status = -1
572538
def send(self, test=None):
        '''
        
        '''
        self._check_values()

        # Set up message dictionary
        json_message = self.to_json_message()

        # if (self.__html_body and not self.__text_body) and self.__multipart:
        #     # TODO: Set up regex to strip html
        #     pass

        # If test is not specified, attempt to read the Django setting
        if test is None:
            try:
                from django.conf import settings as django_settings
                test = getattr(django_settings, "POSTMARK_TEST_MODE", None)
            except ImportError:
                pass

        # If this is a test, just print the message
        if test:
            print('JSON message is:\n%s' % json.dumps(json_message, cls=PMJSONEncoder))
            return

        if self.__template_id:
            endpoint_url = __POSTMARK_URL__ + 'email/withTemplate/'
        else:
            endpoint_url = __POSTMARK_URL__ + 'email'

        # Set up the url Request
        req = Request(
            endpoint_url,
            json.dumps(json_message, cls=PMJSONEncoder).encode('utf8'),
            {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Postmark-Server-Token': self.__api_key,
                'User-agent': self.__user_agent
            }
        )

        # Attempt send
        try:
            # print 'sending request to postmark: %s' % json_message
            result = urlopen(req)
            jsontxt = result.read().decode('utf8')
            result.close()
            if result.code == 200:
                self.message_id = json.loads(jsontxt).get('MessageID', None)
                return True
            else:
                raise PMMailSendException('Return code %d: %s' % (result.code, result.msg))
        except HTTPError as err:
            if err.code == 401:
                raise PMMailUnauthorizedException('Sending Unauthorized - incorrect API key.', err)
            elif err.code == 422:
                try:
                    jsontxt = err.read().decode('utf8')
                    jsonobj = json.loads(jsontxt)
                    desc = jsonobj['Message']
                    error_code = jsonobj['ErrorCode']
                except KeyError:
                    raise PMMailUnprocessableEntityException('Unprocessable Entity: Description not given')

                if error_code == 406:
                    raise PMMailInactiveRecipientException('You tried to send email to a recipient that has been marked as inactive.')

                raise PMMailUnprocessableEntityException('Unprocessable Entity: %s' % desc)
            elif err.code == 500:
                raise PMMailServerErrorException('Internal server error at Postmark. Admins have been alerted.', err)
        except URLError as err:
            if hasattr(err, 'reason'):
                raise PMMailURLException('URLError: Failed to reach the server: %s (See "inner_exception" for details)' % err.reason, err)
            elif hasattr(err, 'code'):
                raise PMMailURLException('URLError: %d: The server couldn\'t fufill the request. (See "inner_exception" for details)' % err.code, err)
            else:
                raise PMMailURLException('URLError: The server couldn\'t fufill the request. (See "inner_exception" for details)', err)
1046882
def mail_message(smtp_server, message, from_address, rcpt_addresses):
    
    if smtp_server[0] == '/':
        # Sending the message with local sendmail
        p = os.popen(smtp_server, 'w')
        p.write(message)
        p.close()
    else:
        # Sending the message using a smtp server
        import smtplib

        server = smtplib.SMTP(smtp_server)
        server.sendmail(from_address, rcpt_addresses, message)
        server.quit()
1075648
def send_html_mail(subject, message, message_html, from_email, recipient_list,
                   priority=None, fail_silently=False, auth_user=None,
                   auth_password=None, headers={}):
    
    from django.utils.encoding import force_text
    from django.core.mail import EmailMultiAlternatives
    from mailer.models import make_message

    priority = get_priority(priority)

    # need to do this in case subject used lazy version of ugettext
    subject = force_text(subject)
    message = force_text(message)

    msg = make_message(subject=subject,
                       body=message,
                       from_email=from_email,
                       to=recipient_list,
                       priority=priority)
    email = msg.email
    email = EmailMultiAlternatives(
        email.subject,
        email.body,
        email.from_email,
        email.to,
        headers=headers
    )
    email.attach_alternative(message_html, "text/html")
    msg.email = email
    msg.save()
    return 1
649386
def send_email(recipients, subject, text_content=None, html_content=None, from_email=None, use_base_template=True, category=None, fail_silently=False, language=None, cc=None, bcc=None, attachments=None, headers=None, bypass_queue=False, bypass_hijacking=False, attach_files=None):
    
    from django.conf import settings
    if not bypass_queue and hasattr(settings, 'MAILING_USE_CELERY') and settings.MAILING_USE_CELERY:
        from celery.execute import send_task
        return send_task('mailing.queue_send_email',[recipients, subject, text_content, html_content, from_email, use_base_template, category, fail_silently, language if language else translation.get_language(), cc, bcc, attachments, headers, bypass_hijacking, attach_files])
    else:

        header_category_value = '%s%s' % (settings.MAILING_HEADER_CATEGORY_PREFIX if hasattr(settings, 'MAILING_HEADER_CATEGORY_PREFIX') else '', category)
        # Check for sendgrid support and add category header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_SENDGRID'):
            send_grid_support = settings.MAILING_USE_SENDGRID
        else:
            send_grid_support = False

        if not headers:
            headers = dict()        
        if send_grid_support and category:
            headers['X-SMTPAPI'] = '{"category": "%s"}' % header_category_value

        # Check for Mailgun support and add label header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_MAILGUN'):
            mailgun_support = settings.MAILING_USE_MAILGUN
        else:
            mailgun_support = False

        if not headers:
            headers = dict()        
        if mailgun_support and category:
            headers['X-Mailgun-Tag'] = header_category_value


        # Ensure recipients are in a list
        # --------------------------------
        if isinstance(recipients, basestring):
            recipients_list = [recipients]
        else:
            recipients_list = recipients

        # Check if we need to hijack the email
        # --------------------------------
        if hasattr(settings, 'MAILING_MAILTO_HIJACK') and not bypass_hijacking:
            headers['X-MAILER-ORIGINAL-MAILTO'] = ','.join(recipients_list)
            recipients_list = [settings.MAILING_MAILTO_HIJACK]

        if not subject:
            raise MailerMissingSubjectError('Subject not supplied')

        # Send ascii, html or multi-part email
        # --------------------------------
        if text_content or html_content:
            if use_base_template:
                prev_language = translation.get_language()
                language and translation.activate(language)
                text_content = render_to_string('mailing/base.txt', {'mailing_text_body': text_content, 'mailing_subject': subject, 'settings': settings}) if text_content else None
                html_content = render_to_string('mailing/base.html', {'mailing_html_body': html_content, 'mailing_subject': subject, 'settings': settings}) if html_content else None
                translation.activate(prev_language)
            msg = EmailMultiAlternatives(subject, text_content if text_content else html_content, from_email if from_email else settings.DEFAULT_FROM_EMAIL, recipients_list, cc=cc, bcc=bcc, attachments=attachments, headers = headers)
            if html_content and text_content:
                msg.attach_alternative(html_content, "text/html")
            elif html_content: # Only HTML
                msg.content_subtype = "html"

            # Attach files through attach_files helper
            # --------------------------------
            if attach_files:
                for att in attach_files:  # attachments are tuples of (filepath, mimetype, filename)
                    with open(att[0], 'rb') as f:
                        content = f.read()
                    msg.attach(att[2], content, att[1])

            # Send email
            # --------------------------------

            msg.send(fail_silently=fail_silently)
        else:
            raise MailerInvalidBodyError('No text or html body supplied.')
216953
def send(mail, server='localhost'):
    
    sender = mail.get_sender()
    rcpt = mail.get_receipients()
    session = smtplib.SMTP(server)
    message = MIMEMultipart()
    message['Subject'] = mail.get_subject()
    message['From'] = mail.get_sender()
    message['To'] = ', '.join(mail.get_to())
    message['Cc'] = ', '.join(mail.get_cc())
    message.preamble = 'Your mail client is not MIME aware.'

    body = MIMEText(mail.get_body().encode("utf-8"), "plain", "utf-8")
    body.add_header('Content-Disposition', 'inline')
    message.attach(body)

    for filename in mail.get_attachments():
        message.attach(_get_mime_object(filename))

    session.sendmail(sender, rcpt, message.as_string())
537139
def send(self):
        
        self.__create()
        email_script = \
            os.path.join(Path(__file__).parents[1], 'scripts', 'sendemail.py')
        if os.path.exists(email_script):
            subprocess.Popen(
                [get_python_path(), email_script, self.__data],
                stdin=None, stdout=None, stderr=None, close_fds=True)
1011298
public static function sendHtmlEmail (\stdClass $emailBody, \stdClass $to, \stdClass $from, \stdClass $replyTo, $SMTPConfig='') : bool
	{
		$mail = new PHPMailer;
		static::setSMTPConfig($mail, $SMTPConfig);
	    $mail->Subject 	= $emailBody->subject;
	    $mail->MsgHTML($emailBody->messageBody);
	    $mail->addAddress($to->email, $to->name);
	    $mail->setFrom($from->email, $from->name);
		$mail->addReplyTo($replyTo->email, $replyTo->name);
		static::$result 		= $mail->send();
		static::$errorMessage 	= $mail->ErrorInfo;
	    return static::$result ? TRUE : FALSE;
	}
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()
386701
boolean sendMail() {

        if(!this.isPropertiesSet()) {
            logger.debug(LOG_PREFIX + ": Required Mail Properties are not set. Attachments will not be sent");
            return false;
        }

        Properties prop = new Properties();
        prop.put("mail.smtp.auth", true);
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", this.host);
        prop.put("mail.smtp.port", this.port);
        prop.put("mail.smtp.ssl.trust", host);

        logger.debug(LOG_PREFIX + ": Mail properties set");

        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        logger.debug(LOG_PREFIX + ": Mail Session Created");

        try {
//			create a default mime message object
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAdd));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAdd));
            message.setSubject(subject);

//          body part for message
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setContent(msg, "text/html");

//          body part for attachments
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            logger.debug(LOG_PREFIX + ": " + this.attachments.length + " attachments found");
            for (File file: this.attachments) {
                attachmentBodyPart.attachFile(file);
            }

//          create a multipart to combine them together
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);
            multipart.addBodyPart(attachmentBodyPart);

            //now set the multipart as the content of the message
            message.setContent(multipart);

//			send the message
            Transport.send(message);

            logger.debug(LOG_PREFIX + ": MESSAGE SENT SUCCESSFULLY");

            return true;

        } catch (Exception e) {
            logger.debug(LOG_PREFIX + ": MESSAGE NOT SENT. " + e.getLocalizedMessage());
            e.printStackTrace();
            return false;
        }

    }
461812
public function send(): void
	{
		/**
		 * Template variables..
		 */
		$this->template->mailData = $this->mailData;

		/**
		 * Stick to convention that Email:
		 * 		/FooMail.php	
		 * 
		 * will have template with path of:
		 * 		/templates/FooMail.latte
		 */
		$mailClassReflection = new \ReflectionClass($this);
		$templateName = $mailClassReflection->getShortName();

		$this->template->setFile(sprintf(
			'%s/templates/%s.latte',
			dirname($mailClassReflection->getFilename()),
			$templateName
		));

		/**
		 * Set body/html body
		 */
		if (version_compare(Engine::VERSION, '2.4.0', '>=')) {
			$this->template->getLatte()->addProvider('uiControl', $this->linkGenerator);
		} else {
			$this->template->_control = $this->linkGenerator;
		}

		$this->message->setHtmlBody((string) $this->template, $this->mailImagesBasePath);

		/**
		 * In case mail sending in on, send message
		 */
		if ($this->config === MailingExtension::CONFIG_BOTH || $this->config === MailingExtension::CONFIG_SEND) {
			$this->mailer->send($this->message);
		}

		/**
		 * In case mail logging is turned on, log message
		 */
		if ($this->config === MailingExtension::CONFIG_LOG || $this->config === MailingExtension::CONFIG_BOTH) {
			$this->logger->log($templateName, $this->message);
		}
	}
323608
def send_email_template(slug, base_url=None, context=None, user=None,
                       to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None, fail_silently=False):
    
    email_template = EmailTemplate.objects.get_for_slug(slug)

    email = email_template.get_email_message(
        base_url, context, user,
        to=to, cc=cc, bcc=bcc,
        attachments=attachments, headers=headers, connection=connection
    )

    return email.send(fail_silently=fail_silently)
38703
def email_template(rcpt, template_path, **kwargs):
    

    subject, content = parse_template(template_path, **kwargs)
    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
                      [rcpt], fail_silently=True)
    return bool(count)
205038
function (template, email, name, vars)
            {
                if (mandrillAPI)
                    mandrillAPI('/messages/send-template', {
                        template_name: template,
                        template_content: [
                            {name: "foo", content: "bar"}
                        ],
                        message: {
                            to: [{
                                email: email,
                                name: name
                            }],
                            from_email: mixinConfig.senderEmail,
                            from_name:  mixinConfig.senderName,
                            global_merge_vars: vars
                        }
                    }).then(function (results) {
                        if (results.length > 0 && results[0].status != "sent")
                            this.log(0, "Mandrill - error sending " + template + " to " + email + " - " +
                                results[0].reject_reason);
                    }.bind(this), function(error) {
                        this.log(0, "Mandrill - error sending " + template + " to " + email + " - " + error.message);
                    }.bind(this));
                else
                    this.log(0, "Mandrill - error sending " + template + " to " + email +
                        " - Missing API Key (should be in environment variable mandrillAPIKey)");
            }