when passing in to/from addresses that are complex objects
 like a Hash or Twitter::Client instance, they will be YAMLed
 and then Base64ed since Mail::Message really only wants
 to play with strings for these fields
176195
def complex_extract(address_container)
      if B64Y.decodable?(address_container)
        {
          decoded: true,
          value: B64Y.decode(address_container)
        }
      else
        {
          decoded: false,
          value: address_container
        }
      end
    end
575880
def hash_for_railsbp(error)
        {
          'linter' => error['message'].gsub(/\((.*)\)/, '').strip.parameterize('_').camelize,
          'severity' => 'warning',
          'reason' => error['message'],
          'column' => 0,
          'line' => error['line_number'].to_i
        }
      end
407771
def serialize(params)
      params.each do |key, value|
        send("#{key}=", value) if respond_to?(key)
      end    
    end
1297991
def [](*args)
      if args.first.kind_of?(Hash) || args.first.kind_of?(Ldaptic::DN)
        send(:/, *args)
      else
        super
      end
    end
104658
function (message) {
      var md = forge.md.sha1.create();
      md.update(message, 'utf8');
      return forge.util.encode64(this._key.sign(md));
    }
1270204
def message
      return {} unless params[:_message]
      begin
        Marshal.load(Merb::Parse.unescape(params[:_message]).unpack("m").first)
      rescue ArgumentError, TypeError
        {}
      end
    end
86832
def recipient_name=(v)
      @recipient_name = nil
      if (v = sanitize(v)) && v.length > 0
        @recipient_name = v
      else
        raise USPSValidationError, "'#{v}' is not a valid string in #{__method__}"
      end
    end
822172
function parseAddresses() {
  var addresses = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

  return (0, _ramda.flatten)([].concat(addresses).map(function (address) {
    if (address && address.address) {
      address = convertAddresses(address);
    }
    return (0, _emailjsAddressparser2.default)(address);
  }));
}
952480
def expanded
            h = Hash.new
            [:id, :email, :api_key, :name, :phone, :password,:states, :approval, :suspend,
            :registration_ip_address, :dates, :some_msg].each do |setting|
                if grouped = self.send("#{setting}").is_a?(Hash)
                    self.send("#{setting}").each {|k,v|   h[k.to_sym] = v}
                else
                    h[setting] = self.send("#{setting}")
                end
            end
            h
        end
308118
def net_smtp
      smtp = Net::SMTP.new(config[:host], config[:port].to_i)
      if config[:tls]
        if smtp.respond_to?(:enable_starttls) # 1.9.x
          smtp.enable_starttls
        elsif smtp.respond_to?(:enable_tls) && smtp.respond_to?(:use_tls?)
          smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE) # 1.8.x with tlsmail
        else
          raise 'Unable to enable TLS, for Ruby 1.8.x install tlsmail'
        end
      end
      smtp.start(config[:domain], config[:user], config[:pass], config[:auth]) { |smtp|
        to = @mail.to.is_a?(String) ? @mail.to.split(/[,;]/) : @mail.to
        smtp.send_message(@mail.to_s, @mail.from.first, to)
      }
    end
489726
function renderMessage(template, user, vars) {
    var appurl = app.getExternalUrl();
    var emailVars = _.defaults(vars || {}, template.templateVars || {}, config.templateVars || {}, {
      'appurl': appurl,
      'settings': app.config.settings
    });
    // XXX should use route resolution fns
    if (user && user.local.signupToken) {
      emailVars.signupLink = appurl + "/verification/" + user.local.signupToken;
    }
    if (user && user.local.resetToken) {
      emailVars.resetLink = appurl + "/forgot/" + user.local.resetToken;
    }

    var msgSubject = swig.render(template.subject, {locals:emailVars});

    var message = {
        from: template.from || config.from,
        to: template.to || user.local.email,
        subject: msgSubject,
    };
    if (template.replyTo) {
      message.replyTo = template.replyTo;
    }

    if (template.templatePath && template.templateName) {
      throw new Error("mail template configuration error: templatePath and templateName cannot both be set");
    }

    if (template.templatePath) {
      message.html = swig.renderFile(template.templatePath, emailVars);
      return message;
    } else {
      message.vars = emailVars;
      message.templateName = template.templateName;
      message.merge_language = template.merge_language || "mailchimp";
      return message;
    }
  }
698218
def stringify_headers headers
      headers.inject({}) do |result, (key, value)|
        if key.is_a? Symbol
          key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
        end
        if 'CONTENT-TYPE' == key.upcase
          target_value = value.to_s
          result[key] = MIME::Types.type_for_extension target_value
        elsif 'ACCEPT' == key.upcase
          # Accept can be composed of several comma-separated values
          if value.is_a? Array
            target_values = value
          else
            target_values = value.to_s.split ','
          end
          result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
        else
          result[key] = value.to_s
        end
        result
      end
    end
619261
def to_response_hash(model, fieldset = self, options = {})
      api_output = {}

      fieldset.each do |field, value|
        next unless allowed_to_render?(fieldset, field, model, options)

        out = process_value(model, value, options)

        if out.respond_to?(:as_api_response)
          sub_template = api_template_for(fieldset, field)
          out = out.as_api_response(sub_template, options)
        end

        api_output[field] = out
      end

      api_output
    end
1324320
function encodeHeaderValue(key) {
  var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

  key = normalizeHeaderKey(key);

  switch (key) {
    case 'From':
    case 'Sender':
    case 'To':
    case 'Cc':
    case 'Bcc':
    case 'Reply-To':
      return convertAddresses(parseAddresses(value));

    case 'Message-Id':
    case 'In-Reply-To':
    case 'Content-Id':
      value = value.replace(/\r?\n|\r/g, ' ');

      if (value.charAt(0) !== '<') {
        value = '<' + value;
      }

      if (value.charAt(value.length - 1) !== '>') {
        value = value + '>';
      }
      return value;

    case 'References':
      value = [].concat.apply([], [].concat(value).map(function () {
        var elm = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
        return elm.replace(/\r?\n|\r/g, ' ').trim().replace(/<[^>]*>/g, function (str) {
          return str.replace(/\s/g, '');
        }).split(/\s+/);
      })).map(function (elm) {
        if (elm.charAt(0) !== '<') {
          elm = '<' + elm;
        }
        if (elm.charAt(elm.length - 1) !== '>') {
          elm = elm + '>';
        }
        return elm;
      });

      return value.join(' ').trim();

    default:
      return (0, _emailjsMimeCodec.mimeWordsEncode)((value || '').toString().replace(/\r?\n|\r/g, ' '), 'B');
  }
}
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
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
278336
def to_hash
      OPTIONS.inject({}) do |hash, option|
        hash.merge(option.to_sym => send(option))
      end
    end