Convert the message to a mime compliant email string
488290
def message(self):
        
        return '\n'.join(
            [self.from_email, str(self.to), self.subject, self.body])
887441
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None):
        """"""
        # TODO Maybe file attachments handling through `files` message_model context var.

        if subject is None:
            subject = u'%s' % _('No Subject')

        if mtype == 'html':
            msg = self.mime_multipart()
            text_part = self.mime_multipart('alternative')
            text_part.attach(self.mime_text(strip_tags(text), _charset='utf-8'))
            text_part.attach(self.mime_text(text, 'html', _charset='utf-8'))
            msg.attach(text_part)

        else:
            msg = self.mime_text(text, _charset='utf-8')

        msg['From'] = self.from_email
        msg['To'] = to
        msg['Subject'] = subject

        if unsubscribe_url:
            msg['List-Unsubscribe'] = '<%s>' % unsubscribe_url

        return msg
1281931
def msg(self, target, message, formatted=True, tags=None):
        """"""
        if formatted:
            message = unescape(message)

        self.send('PRIVMSG', params=[target, message], source=self.nick, tags=tags)
791458
final MimeMessage populateMimeMessage(@Nonnull final Email email, @Nonnull Session session)
			throws MessagingException, UnsupportedEncodingException {
		checkArgumentNotEmpty(email, "email is missing");
		checkArgumentNotEmpty(session, "session is needed, it cannot be attached later");
		
		final MimeMessage message = new MimeMessage(session) {
			@Override
			protected void updateMessageID() throws MessagingException {
				if (valueNullOrEmpty(email.getId())) {
					super.updateMessageID();
				} else {
					setHeader("Message-ID", email.getId());
				}
			}
			
			@Override
			public String toString() {
				try {
					return "MimeMessage<id:" + super.getMessageID() + ", subject:" + super.getSubject() + ">";
				} catch (MessagingException e) {
					throw new AssertionError("should not reach here");
				}
			}
		};
		
		// set basic email properties
		MimeMessageHelper.setSubject(email, message);
		MimeMessageHelper.setFrom(email, message);
		MimeMessageHelper.setReplyTo(email, message);
		MimeMessageHelper.setRecipients(email, message);
		
		populateMimeMessageMultipartStructure(message, email);
		
		MimeMessageHelper.setHeaders(email, message);
		message.setSentDate(new Date());

		if (!valueNullOrEmpty(email.getDkimSigningDomain())) {
			return signMessageWithDKIM(message, email);
		}
		
		return message;
	}
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
1240170
def email(to='medusa@sweeting.me', _from=default_from, subject='BOT MSG', message="Info email", attachments=None):
    """"""
    for attachment in attachments or []:
        filename = attachment.strip()
        try:
            result = run_cmd('uuencode %s %s | mailx -s "%s" %s' % (filename, filename, subject, to))[0]
            return "Sending email From: %s; To: %s; Subject: %s; Attachment: %s (%s)" % (_from, to, subject, filename, result or 'Succeded')
        except Exception as error:
            return str(error)

    if not attachments:
        p = os.popen("/usr/sbin/sendmail -t", "w")
        p.write("From: %s\n" % _from)
        p.write("To: %s\n" % to)
        p.write("Subject: %s\n" % subject)
        p.write("\n")   # blank line separating headers from body
        p.write('%s\n' % message)
        result = p.close()

    if not result:
        return "Sent email From: %s; To: %s; Subject: %s; Attachments: %s)" % (_from, to, subject, ','.join(attachments or []))
    else:
        return "Error: %s. Please fix Postfix:\n %s" % (result, help_str)
665994
public static MimeMessage newMimeMessage(String mailString) throws MessagingException {
        return newMimeMessage(EncodingUtil.toStream(mailString, EncodingUtil.CHARSET_EIGHT_BIT_ENCODING));
    }
422187
def create_email(filepaths, collection_name):
    
    outer = MIMEMultipart()
    outer.preamble = 'Here are some files for you'

    def add_file_to_outer(path):
        if not os.path.isfile(path):
            return

        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        if maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'text':
            # We do this to catch cases where text files have
            # an encoding we can't guess correctly.
            try:
                fp = open(path, 'r')
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            except UnicodeDecodeError:
                fp = open(path, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)
                fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment',
                filename=os.path.basename(path))
        outer.attach(msg)

    outer.attach(MIMEText("Here are some files I've thrown at you."))
    
    for path in filepaths:
        add_file_to_outer(path)

    return outer
1179274
def _construct_email(self, email, **extra):
        
        if isinstance(email, dict):
            email = Email(manager=self._manager, **email)
        elif isinstance(email, (MIMEText, MIMEMultipart)):
            email = Email.from_mime(email, self._manager)
        elif not isinstance(email, Email):
            raise ValueError
        email._update(extra)
        return email.as_dict()
854287
def file_body(message, file)
      file_name = File.basename(file.path)
      mime_type = MimeMagic.by_path(file_name)
      file_content = Base64.encode64(file.read)

      body =  ["--#{BOUNDARY}"]
      body << 'Content-Type: application/json; charset=UTF-8'
      body << 'Content-Disposition: attachment; name="metadata"'
      body << ''
      body << message
      body << "--#{BOUNDARY}"
      body << "Content-Type: #{mime_type}; charset=UTF-8"
      body << 'Content-Transfer-Encoding: base64'
      body << %{Content-Disposition: attachment; name="file"; filename="#{file_name}"}
      body << ''
      body << file_content
      body << "--#{BOUNDARY}--"
      body.join("\n")
    end
1330308
def get_smtp_mail(self):
        
        header = self.get_smtp_header()
        body = self.get_body().replace('\n', '\r\n')
        return header + '\r\n' + body + '\r\n'
652398
public MimeMessage getMessage(Session session) {

		Assert.notNull(emails, "No email address given!");

		Map<String, String> recipients = emails.get(Message.RecipientType.TO);
		Assert.isTrue(recipients != null && recipients.size() > 0, "Missing to email address(es)!");

		boolean found = false;
		for (String email : recipients.keySet()) {
			if (!excluded(email)) { // at least one address is not excluded
				found = true;
				break;
			}
		}

		Assert.isTrue(found, "All to email address(es) are excluded!");

		if (StringUtils.isNullOrEmptyTrimmed(fromName)) {
			fromName = fromEmail;
		}

		Assert.notNullOrEmptyTrimmed(fromEmail, "Missing from email address!");
		Assert.notNullOrEmptyTrimmed(subject, "Missing email subject!");

		Assert.isTrue(!StringUtils.isNullOrEmptyTrimmed(content) || !StringUtils.isNullOrEmptyTrimmed(htmlContent), "Missing email content!");

		subject = subject.trim();
		content = content != null ? content.trim() : null;
		htmlContent = htmlContent != null ? htmlContent.trim() : null;

		log.info("Sending from: " + fromEmail + " (" + fromName + ")");

		MimeMessage msg = new MimeMessage(session);

		// FROM:
		try {
			msg.setFrom(new InternetAddress(fromEmail, fromName, UTF_8));

			// TO:
			addRecipients(Message.RecipientType.TO, msg);
			// CC:
			addRecipients(Message.RecipientType.CC, msg);
			// BCC:
			addRecipients(Message.RecipientType.BCC, msg);

			//msg.setSubject(subject, UTF_8);
			msg.setSubject(MimeUtility.encodeText(subject, UTF_8, "Q"));

			// add headers
			if (headers != null && headers.size() > 0) {
				for (String name : headers.keySet()) {
					msg.addHeader(name, headers.get(name));
				}
			}

			try {
				// simple message .. no attachment and only content or html content
				if ((attachments == null || attachments.size() == 0) &&
				    ((htmlContent == null && content != null) ||
				     (htmlContent != null && content == null))) {

					if (StringUtils.isNullOrEmptyTrimmed(content)) {
						msg.addHeader("Content-Type", "text/html");
						msg.setContent(htmlContent, "text/html; charset=" + UTF_8);
					} else {
						msg.setContent(content, "text/plain; charset=" + UTF_8);
					}
				}
				// Compose multipart message
				else {
					// must be in correct order from lower fidelity to higher
					Multipart multipart = new MimeMultipart();

					if (!StringUtils.isNullOrEmptyTrimmed(content)) {
						MimeBodyPart contentPart = new MimeBodyPart();
						contentPart.setContent(content, "text/plain; charset=" + UTF_8);
						multipart.addBodyPart(contentPart);
					}

					if (!StringUtils.isNullOrEmptyTrimmed(htmlContent)) {
						MimeBodyPart htmlPart = new MimeBodyPart();
						htmlPart.setContent(htmlContent, "text/html; charset=" + UTF_8);
						multipart.addBodyPart(htmlPart);
					}

					if (attachments != null && attachments.size() > 0) {
						for (MailAttachment attachment : attachments) {

							// add attachment
							MimeBodyPart part = new MimeBodyPart();
							if (attachment.fileName != null) {
								part.setFileName(attachment.fileName);
							}
							DataSource src = new ByteArrayDataSource(attachment.content, attachment.type);
							part.setDataHandler(new DataHandler(src));
							multipart.addBodyPart(part);
						}
					}

					msg.setContent(multipart);
				}

				// if save is not called mime part headers are not updated
				msg.saveChanges();
				// see: http://stackoverflow.com/questions/5028670/how-to-set-mimebodypart-contenttype-to-text-html
			}
			catch (Exception e) {
				log.error("Failed to add attachment to mail message: ", e);
				throw new IllegalArgumentException(e.getMessage(), e);
			}

		}
		catch (MessagingException | UnsupportedEncodingException e) {
			log.error("Mail massage build failed!", e);
			throw new IllegalArgumentException(e.getMessage(), e);
		}

		return msg;
	}
173021
def MessageToJson(message, include_fields=None):
    """"""
    result = _ProtoJsonApiTools.Get().encode_message(message)
    return _IncludeFields(result, message, include_fields)
419714
protected static <Message extends PMessage<Message, CField>>
    String asString(Message message) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PRETTY_SERIALIZER.serialize(baos, message);
        return new String(baos.toByteArray(), UTF_8);
    }
1348038
def canonicalize(message):
    

    if message.is_multipart() \
            or message.get('Content-Transfer-Encoding') != 'binary':

        return mime_to_bytes(message, 0).replace(
            b'\r\n', b'\n').replace(b'\r', b'\n').replace(b'\n', b'\r\n')
    else:
        message_header = ''
        message_body = message.get_payload(decode=True)
        for k, v in message.items():
            message_header += '{}: {}\r\n'.format(k, v)
        message_header += '\r\n'
        return message_header.encode('utf-8') + message_body
375429
def _send(self, email_message):
        """"""
        if not email_message.recipients():
            return False
        from_email = sanitize_address(email_message.from_email, email_message.encoding)

        to_recipients = [sanitize_address(addr, email_message.encoding)
                      for addr in email_message.to]

        try:
            post_data = []
            post_data.append(('to', (",".join(to_recipients)),))
            if email_message.bcc:
                bcc_recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.bcc]
                post_data.append(('bcc', (",".join(bcc_recipients)),))
            if email_message.cc:
                cc_recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.cc]
                post_data.append(('cc', (",".join(cc_recipients)),))
            post_data.append(('text', email_message.body,))
            post_data.append(('subject', email_message.subject,))
            post_data.append(('from', from_email,))
            # get our recipient variables if they were passed in
            recipient_variables = email_message.extra_headers.pop('recipient_variables', None)
            if recipient_variables is not None:
                post_data.append(('recipient-variables', recipient_variables, ))

            for name, value in self._map_smtp_headers_to_api_parameters(email_message):
                post_data.append((name, value, ))

            if hasattr(email_message, 'alternatives') and email_message.alternatives:
                for alt in email_message.alternatives:
                    if alt[1] == 'text/html':
                        post_data.append(('html', alt[0],))
                        break

            # Map Reply-To header if present
            try:
                if email_message.reply_to:
                    post_data.append((
                        "h:Reply-To",
                        ", ".join(map(force_text, email_message.reply_to)),
                    ))
            except AttributeError:
                pass

            if email_message.attachments:
                for attachment in email_message.attachments:
                    post_data.append(('attachment', (attachment[0], attachment[1],)))
                content, header = encode_multipart_formdata(post_data)
                headers = {'Content-Type': header}
            else:
                content = post_data
                headers = None

            response = requests.post(self._api_url + "messages",
                    auth=("api", self._access_key),
                    data=content, headers=headers)
        except:
            if not self.fail_silently:
                raise
            return False

        if response.status_code != 200:
            if not self.fail_silently:
                raise MailgunAPIError(response)
            return False

        return True
577951
def email(sender=None, receivers=(), cc=(), bcc=(),
          subject=None, content=None, encoding='utf8',
          attachments=()):
    
    enclosure = [HTML(content, encoding)]
    enclosure.extend(Attachment(k) for k in attachments)
    return Collection(
        *enclosure,
        headers=[
            headers.subject(subject),
            headers.sender(sender),
            headers.to(*receivers),
            headers.cc(*cc),
            headers.bcc(*bcc),
            headers.date(),
            headers.message_id(),
        ]
    )