Minimum required to send an email
774352
public static Mail buildHelloEmail() throws IOException {
    Email from = new Email("test@example.com");
    String subject = "Hello World from the SendGrid Java Library";
    Email to = new Email("test@example.com");
    Content content = new Content("text/plain", "some text here");
    // Note that when you use this constructor an initial personalization object
    // is created for you. It can be accessed via
    // mail.personalization.get(0) as it is a List object
    Mail mail = new Mail(from, subject, to, content);
    Email email = new Email("test2@example.com");
    mail.personalization.get(0).addTo(email);

    return mail;
  }
337169
def send(email, subject, opts = {})
      if email.nil? or subject.nil?
        raise ArgumentError, 'Email Address or Subject is missing'
      else
        message = {
          from_name: Octo.get_config(:email_sender).fetch(:name),
          from_email: Octo.get_config(:email_sender).fetch(:email),

          subject: subject,

          text: opts.fetch('text', nil),
          html: opts.fetch('html', nil),

          to: [{
            email: email,
            name: opts.fetch('name', nil)
          }]
        }
        # Pass the message to resque only when mandrill key is present
        _mandrill_config = ENV['MANDRILL_API_KEY'] || Octo.get_config(:mandrill_api_key)
        if _mandrill_config and !_mandrill_config.empty?
          enqueue_msg(message)
        end
      end
    end
435252
def send(self, email=None):
        
        if email is None and self.send_as_one:
            self.smtp.send_message(
                self.multipart, self.config['EMAIL'], self.addresses)
        elif email is not None and self.send_as_one is False:
            self.smtp.send_message(
                self.multipart, self.config['EMAIL'], email)
        self.multipart = MIMEMultipart('alternative')
1129118
function send() {
		// Check form for errors
		if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
		if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
		if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');

		// Set the private key in common object
		common.privateKey = $("#privateKey").val();

		// Check private key for errors
		if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
    	if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');

		// Set the cleaned amount into transfer transaction object
		transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());

		// Recipient address must be clean (no hypens: "-")
		transferTransaction.recipient = nem.model.address.clean($("#recipient").val());

		// Set message
		transferTransaction.message = $("#message").val();

		// Prepare the updated transfer transaction object
		var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);

		// Serialize transfer transaction and announce
		nem.model.transactions.send(common, transactionEntity, endpoint).then(function(res){
			// If code >= 2, it's an error
			if (res.code >= 2) {
				alert(res.message);
			} else {
				alert(res.message);
			}
		}, function(err) {
			alert(err);
		});
	}
687820
def send_mail(recipient, sender, subject="", content="", smtp_host="127.0.0.1", smtp_port=25):
    
    try:
        server = smtplib.SMTP(smtp_host, smtp_port)
    except Exception as e:
        logger = logging.getLogger(__name__)
        logger.warning("cannot create SMTP server: {}".format(e))
        return False

    header = "From: {}\r\nTo: {}\r\nSubject: {}\r\n\r\n".format(sender, recipient, subject)
    server.sendmail(sender, recipient, header + content)

    return True
1238964
function send_mail(opts) {
	var Q = require('q');
	var nodemailer = require("nodemailer");

	var smtpTransport = nodemailer.createTransport("SMTP", config.smtp);
	
	// setup e-mail data with unicode symbols
	var mailOptions = {
		from: opts.from,
		to: opts.to,
		subject: opts.subject,
		text: opts.text,
		html: opts.html
	};
	
	// send mail with defined transport object
	var defer = Q.defer();
	try {
		util.debug('Calling smtpTransport.sendMail()...');
		smtpTransport.sendMail(mailOptions, function(error, response){
			util.debug('End of smtpTransport.sendMail()');
			if(error){
				defer.reject(error);
				return;
			}
			defer.resolve(response);
		});
	} catch(err) {
		defer.reject(err);
	}
	return defer.promise.fin(function() { smtpTransport.close(); });
}
850818
def deliver!(mail)
      mg_message = Railgun.transform_for_mailgun(mail)
      response = @mg_client.send_message(@domain, mg_message)

      if response.code == 200 then
        mg_id = response.to_h['id']
        mail.message_id = mg_id
      end
      response
    end
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.')
424200
def send_form_email(params, subject)
        body = []
        params.each_pair { |k,v| body << "#{k}: #{v}"  }
        BasicMailer.mail(:subject => subject, :body => body.join("\n")).deliver
      end
560063
def send_mail(subject, body_text, addr_from, recipient_list,
              fail_silently=False, auth_user=None, auth_password=None,
              attachments=None, body_html=None, html_message=None,
              connection=None, headers=None):
    

    # Make sure only one HTML option is specified
    if body_html is not None and html_message is not None:  # pragma: no cover
        raise ValueError("You cannot specify body_html and html_message at "
                         "the same time. Please only use html_message.")

    # Push users to update their code
    if body_html is not None:  # pragma: no cover
        warn("Using body_html is deprecated; use the html_message argument "
             "instead. Please update your code.", DeprecationWarning)
        html_message = body_html

    # Allow for a single address to be passed in.
    if isinstance(recipient_list, six.string_types):
        recipient_list = [recipient_list]

    connection = connection or get_connection(
        username=auth_user, password=auth_password,
        fail_silently=fail_silently)

    # Obtain a list of the recipients that have gpg keys installed.
    key_addresses = {}
    if USE_GNUPG:
        from email_extras.models import Address
        key_addresses = dict(Address.objects.filter(address__in=recipient_list)
                                            .values_list('address', 'use_asc'))
        # Create the gpg object.
        if key_addresses:
            gpg = GPG(gnupghome=GNUPG_HOME)
            if GNUPG_ENCODING is not None:
                gpg.encoding = GNUPG_ENCODING

    # Check if recipient has a gpg key installed
    def has_pgp_key(addr):
        return addr in key_addresses

    # Encrypts body if recipient has a gpg key installed.
    def encrypt_if_key(body, addr_list):
        if has_pgp_key(addr_list[0]):
            encrypted = gpg.encrypt(body, addr_list[0],
                                    always_trust=ALWAYS_TRUST)
            if encrypted == "" and body != "":  # encryption failed
                raise EncryptionFailedError("Encrypting mail to %s failed.",
                                            addr_list[0])
            return smart_text(encrypted)
        return body

    # Load attachments and create name/data tuples.
    attachments_parts = []
    if attachments is not None:
        for attachment in attachments:
            # Attachments can be pairs of name/data, or filesystem paths.
            if not hasattr(attachment, "__iter__"):
                with open(attachment, "rb") as f:
                    attachments_parts.append((basename(attachment), f.read()))
            else:
                attachments_parts.append(attachment)

    # Send emails - encrypted emails needs to be sent individually, while
    # non-encrypted emails can be sent in one send. So the final list of
    # lists of addresses to send to looks like:
    # [[unencrypted1, unencrypted2, unencrypted3], [encrypted1], [encrypted2]]
    unencrypted = [addr for addr in recipient_list
                   if addr not in key_addresses]
    unencrypted = [unencrypted] if unencrypted else unencrypted
    encrypted = [[addr] for addr in key_addresses]
    for addr_list in unencrypted + encrypted:
        msg = EmailMultiAlternatives(subject,
                                     encrypt_if_key(body_text, addr_list),
                                     addr_from, addr_list,
                                     connection=connection, headers=headers)
        if html_message is not None:
            if has_pgp_key(addr_list[0]):
                mimetype = "application/gpg-encrypted"
            else:
                mimetype = "text/html"
            msg.attach_alternative(encrypt_if_key(html_message, addr_list),
                                   mimetype)
        for parts in attachments_parts:
            name = parts[0]
            if key_addresses.get(addr_list[0]):
                name += ".asc"
            msg.attach(name, encrypt_if_key(parts[1], addr_list))
        msg.send(fail_silently=fail_silently)
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;
        }

    }
301403
@Override
	public MailSendResult send(MailMessage message) {

		Assert.notNull(message, "Missing mail message!");

		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.port", smtpPort);

		Session session = getSession(props, smtpUsername, smtpPassword);

		try {
			// build mime message
			Message msg = message.getMessage(session);

			Enumeration enumer = msg.getAllHeaders();
			while (enumer.hasMoreElements()) {
				Header header = (Header) enumer.nextElement();
				log.info(header.getName() + ": " + header.getValue());
			}

			log.info("Getting transport...");

			Transport transport = session.getTransport("smtp");
			log.info("Connecting to SMTP server: " + smtpHost + ":" + smtpPort);

			transport.connect();
			transport.sendMessage(msg, msg.getAllRecipients());

			log.info("Closing transport...");
			transport.close();
		}
		catch (Exception e) {

			log.error(e.getMessage(), e);
			return MailSendResult.fail();
		}

		return MailSendResult.ok();

	}
181676
def _send(self, email_message):
		""""""
		if not email_message.recipients():
			return False
		from_email = email_message.from_email
		recipients = email_message.recipients()
		try:
			self.connection.messages.create(
				to=recipients,
				from_=from_email,
				body=email_message.body
			)
		except Exception:
			if not self.fail_silently:
				raise
			return False
		return True
272463
public void send(final MailInfo mailInfo) {
		try {
			final MultiPartEmail email = new MultiPartEmail();
			email.setCharset("utf-8");
			mailInfo.fillEmail(email);
			email.send();
		} catch (Exception e) {
			JK.throww(e);
		}
	}
924978
def send_mail(subject, body, smtp_server, user, password, from_addr, to_addrs):
    ''' 
    '''
    logging.info('Send status E-Mail (' + subject + ')')
    content = string.join((
        "From: %s" % from_addr,
        "To: %s" % ','.join(to_addrs),  # comma separated according to RFC822
        "Subject: %s" % subject,
        "",
        body),
        "\r\n")
    server = smtplib.SMTP_SSL(smtp_server)
    server.login(user, password)
    server.sendmail(from_addr, to_addrs, content)
    server.quit()
732354
def send_messages(self, messages):
        """"""
        msg_count = 0
        for message in messages:  # .message() triggers header validation
            message.message()
            email.outbox.append(message)
            msg_count += 1

        return msg_count
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)