Creates a SMTP transport object for Nodemailer

@constructor
@param {Object} options Connection options
762429
function SMTPTransport(options) {
    EventEmitter.call(this);

    options = options || {};
    if (typeof options === 'string') {
        options = {
            url: options
        };
    }

    var urlData;
    var service = options.service;

    if (typeof options.getSocket === 'function') {
        this.getSocket = options.getSocket;
    }

    if (options.url) {
        urlData = shared.parseConnectionUrl(options.url);
        service = service || urlData.service;
    }

    this.options = assign(
        false, // create new object
        options, // regular options
        urlData, // url options
        service && wellknown(service) // wellknown options
    );

    this.logger = shared.getLogger(this.options);

    // temporary object
    var connection = new SMTPConnection(this.options);

    this.name = 'SMTP';
    this.version = packageData.version + '[client:' + connection.version + ']';
}
1069034
function sendMail(object) {
    if (!(mailer instanceof mail.GhostMailer)) {
        mailer = new mail.GhostMailer();
    }

    return mailer.send(object.mail[0].message).catch((err) => {
        if (mailer.state.usingDirect) {
            notificationsAPI.add(
                {
                    notifications: [{
                        type: 'warn',
                        message: [
                            common.i18n.t('warnings.index.unableToSendEmail'),
                            common.i18n.t('common.seeLinkForInstructions', {link: 'https://docs.ghost.org/mail/'})
                        ].join(' ')
                    }]
                },
                {context: {internal: true}}
            );
        }

        return Promise.reject(err);
    });
}
275266
function EmailInput(options) {
    MultipleInput.call(
        this,
        assign(
            {
                createTokenItem: createEmailItem,
                showDropdown: false,
                tokenizer: emailTokenizer
            },
            options
        )
    );

    this.events.on('blur', function() {
        var input = this.input;
        if (input && isValidEmail(lastWord(input.value))) {
            this.add(createEmailItem(input.value));
        }
    });
}
563780
function (options, callbackFn) {
            var self = this;

            //compensate for optional options parm
            if (typeof options === 'function') {
                callbackFn = options;
                options = {};
            }

            //assign default port
            options.port = options.port || 1061;
            options.host = options.host || 'localhost';
            options.hostAndPort = 'http://' + options.host + ':' + options.port;
            options.eventStreamPath = require('path').normalize(__dirname + '/../temp/events.txt');
            options.phantomjsPath = options.phantomjsPath || 'phantomjs';

            options.debug && console.log('creating proxy to %s', options.hostAndPort);

            this.options = options;

            //try starting server
            createServer.call(self, options, function (proxy) {
                callbackFn.call(self, proxy);
            });

            return this;//return this to chain end
        }
196924
function Transport (opts) {
  this.path = opts.path;
  this.host = opts.host;
  this.port = opts.port;
  this.secure = opts.secure;
  this.query = opts.query;
  this.timestampParam = opts.timestampParam;
  this.timestampRequests = opts.timestampRequests;
  this.readyState = '';
}
136419
function sendMail (template, locals, options, callback) {
  var self = this
  this.render(template, locals, function (err, html, text) {
    if (err) { return callback(err) }

    self.transport.sendMail({
      from: options.from || defaultFrom,
      to: options.to,
      subject: options.subject,
      html: html,
      text: text
    }, callback)
  })
}
165561
function init(options){
	options = util._extend({ssl:null, port:12345}, options);
	var serverWorkers = {}; // save main server sockets
	var clientSocket = []; // save local server socket
	var clientOptions = []; // save optioin obj
	var wsServer;
	if(options.ssl)
		wsServer = require('https').createServer(options.ssl);
	else wsServer = require('http').createServer();
	var io = require('socket.io')(wsServer);
	
	if(options.auth)	
	io.set('authorization', function (handshakeData, callback) {
		if(handshakeData.url.match('username='+options.auth.username+'&password='+options.auth.password))
        	callback(null, true); // error first callback style 
        else callback('no auth', false);
    });

	io.on('connection', function(socket){
		// 0. save server sockets & local socket
		socket.on('init', function(data){
			if(data._type == 'localServer'){
				socket._type = 'localServer';
				if(clientSocket.length>0)
					clientSocket.slice(-1)[0].emit('hold');			
				// then handle new one
				clientSocket.push(socket);
				clientOptions.push(data);
				// inform server the new client
				for(i in serverWorkers)
					serverWorkers[i].emit('client', data);
			}else if(data._type == 'server'){
				socket._type = 'server';
				serverWorkers[socket.id] = socket;
			}else{
				// ignore this connection
			}
		})
		// handle req from server, relay data to client
		socket.on('req', function(data){
			if(clientSocket.length > 0){
				data._sid = socket.id;
				clientSocket.slice(-1)[0].emit('req', data)
			}
		})
		// handle res from client, relay the data to the server
		socket.on('res', function(data){
			if(serverWorkers[data._sid])
				serverWorkers[data._sid].emit('res', data);
		});
		socket.on('disconnect', function(reason){
			if(socket._type == 'localServer'){
				var last = false;
				for(i in clientSocket){
					if(socket.id == clientSocket[i].id){
						if(i == clientSocket.length-1)
							last = true;
						clientSocket.splice(i, 1);
						clientOptions.splice(i,1);
						break;
					}
				}
				if(clientSocket.length > 0 && clientOptions.length > 0){
					if(last)
						clientSocket.slice(-1)[0].emit('back');	
					for(i in serverWorkers)
						serverWorkers[i].emit('client', clientOptions.slice(-1)[0]);
				}
				else
					for(i in serverWorkers)
						serverWorkers[i].emit('client', false);
			}
			else if(socket._type == 'server')
				delete serverWorkers[socket.id];
		});
	});
	wsServer.listen(options.port).on('listening', function(){
		options.listening ? options.listening() : noop();
		//console.log('[NLT] Server is ready on port ' + options.port);
	}).on('error', function(e){
		options.error ? options.error(e) : noop();
		//console.log('[NLT] Setup error', e)
	});
}
1105940
function SMTPPool(options) {
    EventEmitter.call(this);

    options = options || {};
    if (typeof options === 'string') {
        options = {
            url: options
        };
    }

    var urlData;
    var service = options.service;

    if (typeof options.getSocket === 'function') {
        this.getSocket = options.getSocket;
    }

    if (options.url) {
        urlData = shared.parseConnectionUrl(options.url);
        service = service || urlData.service;
    }

    this.options = assign(
        false, // create new object
        options, // regular options
        urlData, // url options
        service && wellknown(service) // wellknown options
    );

    this.options.maxConnections = this.options.maxConnections || 5;
    this.options.maxMessages = this.options.maxMessages || 100;

    this.logger = this.options.logger = shared.getLogger(this.options);

    // temporary object
    var connection = new SMTPConnection(this.options);

    this.name = 'SMTP (pool)';
    this.version = packageData.version + '[client:' + connection.version + ']';

    this._rateLimit = {
        counter: 0,
        timeout: null,
        waiting: [],
        checkpoint: false
    };
    this._closed = false;
    this._queue = [];
    this._connections = [];
    this._connectionCounter = 0;

    this.idling = true;

    setImmediate(function () {
        if (this.idling) {
            this.emit('idle');
        }
    }.bind(this));
}
408839
function Email (options) {
  this.action = options.action || SEND_EMAIL_ACTION;
  this.key = options.key;
  this.secret = options.secret;
  this.amazon = options.amazon;
  this.from = options.from;
  this.subject = options.subject;
  this.message = options.message;
  this.altText = options.altText;
  this.rawMessage = options.rawMessage;
  this.configurationSet = options.configurationSet;
  this.messageTags = options.messageTags;
  this.extractRecipient(options, 'to');
  this.extractRecipient(options, 'cc');
  this.extractRecipient(options, 'bcc');
  this.extractRecipient(options, 'replyTo');
}
1281402
function buildSnsDestination(options) {

  let sns = {
    Resources: {},
    Parameters: {},
    Variables: {},
    Policies: []
  };

  if (options.destinations && options.destinations.sns) {
    for (let destination in options.destinations.sns) {
      sns.Parameters[destination + 'Email'] = {
        Type: 'String',
        Description:  options.destinations.sns[destination].Description
      };

      sns.Policies.push({
        PolicyName: destination + 'TopicPermissions',
        PolicyDocument: {
          Statement: [
            {
              Effect: 'Allow',
              Action: 'sns:Publish',
              Resource: cf.ref(options.name)
            }
          ]
        }
      });

      sns.Resources[destination + 'Topic'] = {
        Type: 'AWS::SNS::Topic',
        Properties: {
          TopicName: cf.join('-', [cf.stackName, destination]),
          Subscription: [
            {
              Endpoint: cf.ref(destination + 'Email'),
              Protocol: 'email'
            }
          ]
        }
      };

      sns.Variables[destination + 'Topic'] = cf.ref(destination + 'Topic');
    }
    return sns;
  }
}
26646
function checkEmail(msg, node) {
                if (node.protocol === 'POP3') {
                    checkPOP3(msg);
                } else if (node.protocol === 'IMAP') {
                    console.log('Inside checkEmail');
                    imap = new Imap({
                        user: node.userid,
                        password: node.password,
                        host: node.server,
                        port: node.port,
                        tls: node.useSSL,
                        tlsOptions: {rejectUnauthorized: false},
                        connTimeout: (node.repeat - 10),
                        authTimeout: (node.repeat - 10),
                    });

                    imap.on('error', function(err) {
                        if (err.errno !== 'ECONNRESET') {
                            node.log(err);
                            node.status({fill: 'red', shape: 'ring', text: 'email.status.connecterror'});
                        }
                    });

                    checkIMAP(msg, node.attachment);
                }
            }
996097
function MSPassportStrategy(options) {
  Strategy.call(this);
  this.name = "mspassport";
  
  var default_options = {
        protocol : "querystring",
        protocolHandler : function() { self.fail("protocolHandler must be implemented if protocol === 'custom'") }        
  };
    
  this.options = _defaults(default_options, options);
}
1316159
function Server(options) {
  options = util._extend({}, options);

  this._log = (options.log || defaultLogger).child({ component: 'http' });
  this._settings = options.settings;

  var start = this._start.bind(this);
  var fallback = this._fallback.bind(this);

  // HTTP2 over TLS (using NPN or ALPN)
  if ((options.key && options.cert) || options.pfx) {
    this._log.info('Creating HTTP/2 server over TLS');
    this._mode = 'tls';
    options.ALPNProtocols = supportedProtocols;
    options.NPNProtocols = supportedProtocols;
    options.ciphers = options.ciphers || cipherSuites;
    options.honorCipherOrder = (options.honorCipherOrder != false);
    this._server = https.createServer(options);
    this._originalSocketListeners = this._server.listeners('secureConnection');
    this._server.removeAllListeners('secureConnection');
    this._server.on('secureConnection', function(socket) {
      var negotiatedProtocol = socket.alpnProtocol || socket.npnProtocol;
      // It's true that the client MUST use SNI, but if it doesn't, we don't care, don't fall back to HTTP/1,
      // since if the ALPN negotiation is otherwise successful, the client thinks we speak HTTP/2 but we don't.
      if (negotiatedProtocol === protocol.VERSION) {
        start(socket);
      } else {
        fallback(socket);
      }
    });
    this._server.on('request', this.emit.bind(this, 'request'));

    forwardEvent('error', this._server, this);
    forwardEvent('listening', this._server, this);
  }

  // HTTP2 over plain TCP
  else if (options.plain) {
    this._log.info('Creating HTTP/2 server over plain TCP');
    this._mode = 'plain';
    this._server = net.createServer(start);
  }

  // HTTP/2 with HTTP/1.1 upgrade
  else {
    this._log.error('Trying to create HTTP/2 server with Upgrade from HTTP/1.1');
    throw new Error('HTTP1.1 -> HTTP2 upgrade is not yet supported. Please provide TLS keys.');
  }

  this._server.on('close', this.emit.bind(this, 'close'));
}
574156
public function send($transporter='', $options=array())
	{
		$transporter = $transporter ? $transporter : \Config::get('mailer');

		if (is_object($transporter) && ($transporter instanceof \Swift_Transport))
		{
			// We were given a valid tranport mechanisms, so just use it
			$transport = $transporter;
		}
		elseif (is_string($transporter) && self::hasTrasporter($transporter))
		{
			$transport = self::getTrasporter($transporter);
		}
		else
		{
			switch (strtolower($transporter))
			{
				case 'smtp':
					if (!isset($options['host']))
					{
						$options['host'] = \Config::get('smtphost');
					}
					if (!isset($options['port']))
					{
						$options['port'] = \Config::get('smtpport');
					}
					if (!isset($options['username']))
					{
						$options['username'] = \Config::get('smtpuser');
					}
					if (!isset($options['password']))
					{
						$options['password'] = \Config::get('smtppass');
					}

					if (!empty($options))
					{
						$transport = \Swift_SmtpTransport::newInstance($options['host'], $options['port']);
						$transport->setUsername($options['username'])
						          ->setPassword($options['password']);
					}
				break;

				case 'sendmail':
					if (!isset($options['command']))
					{
						$options['command'] = '/usr/sbin/exim -bs';
					}
					$transport = \Swift_SendmailTransport::newInstance($options['command']);
				break;

				case 'mail':
				default:
					$transport = \Swift_MailTransport::newInstance();
					//set mail additional args (mail return path - used for bounces)
					//$transport->setExtraParams('-f hubmail-bounces@' . $_SERVER['HTTP_HOST']);
				break;
			}

			if (!($transport instanceof \Swift_Transport))
			{
				throw new \InvalidArgumentException('Invalid transport specified');
			}
		}

		$mailer = \Swift_Mailer::newInstance($transport);
		$result = $mailer->send($this, $this->_failures);

		if ($result)
		{
			\Log::info(sprintf('Mail sent to %s', json_encode($this->getTo())));
		}
		else
		{
			\Log::error(sprintf('Failed to mail %s', json_encode($this->getTo())));
		}

		return $result;
	}
680208
function SockJS(url, protocols, options) {
  if (!(this instanceof SockJS)) {
    return new SockJS(url, protocols, options);
  }
  if (arguments.length < 1) {
    throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  }
  EventTarget.call(this);

  this.readyState = SockJS.CONNECTING;
  this.extensions = '';
  this.protocol = '';

  // non-standard extension
  options = options || {};
  if (options.protocols_whitelist) {
    log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  }
  this._transportsWhitelist = options.transports;
  this._transportOptions = options.transportOptions || {};

  var sessionId = options.sessionId || 8;
  if (typeof sessionId === 'function') {
    this._generateSessionId = sessionId;
  } else if (typeof sessionId === 'number') {
    this._generateSessionId = function() {
      return random.string(sessionId);
    };
  } else {
    throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  }

  this._server = options.server || random.numberString(1000);

  // Step 1 of WS spec - parse and validate the url. Issue #8
  var parsedUrl = new URL(url);
  if (!parsedUrl.host || !parsedUrl.protocol) {
    throw new SyntaxError("The URL '" + url + "' is invalid");
  } else if (parsedUrl.hash) {
    throw new SyntaxError('The URL must not contain a fragment');
  } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
    throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  }

  var secure = parsedUrl.protocol === 'https:';
  // Step 2 - don't allow secure origin with an insecure protocol
  if (loc.protocol === 'https:' && !secure) {
    throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  }

  // Step 3 - check port access - no need here
  // Step 4 - parse protocols argument
  if (!protocols) {
    protocols = [];
  } else if (!Array.isArray(protocols)) {
    protocols = [protocols];
  }

  // Step 5 - check protocols argument
  var sortedProtocols = protocols.sort();
  sortedProtocols.forEach(function(proto, i) {
    if (!proto) {
      throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
    }
    if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
      throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
    }
  });

  // Step 6 - convert origin
  var o = urlUtils.getOrigin(loc.href);
  this._origin = o ? o.toLowerCase() : null;

  // remove the trailing slash
  parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));

  // store the sanitized url
  this.url = parsedUrl.href;

  // Step 7 - start connection in background
  // obtain server info
  // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  this._urlInfo = {
    nullOrigin: !browser.hasDomain()
  , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  };

  this._ir = new InfoReceiver(this.url, this._urlInfo);
  this._ir.once('finish', this._receiveInfo.bind(this));
}
664669
function PeerOptions(options) {
  if (!(this instanceof PeerOptions))
    return new PeerOptions(options);

  this.network = Network.primary;
  this.logger = Logger.global;

  this.createSocket = tcp.createSocket;
  this.version = common.PROTOCOL_VERSION;
  this.services = common.LOCAL_SERVICES;
  this.agent = common.USER_AGENT;
  this.noRelay = false;
  this.spv = false;
  this.compact = false;
  this.headers = false;
  this.banScore = common.BAN_SCORE;

  this.getHeight = PeerOptions.getHeight;
  this.isFull = PeerOptions.isFull;
  this.hasWitness = PeerOptions.hasWitness;
  this.createNonce = PeerOptions.createNonce;
  this.hasNonce = PeerOptions.hasNonce;
  this.getRate = PeerOptions.getRate;

  if (options)
    this.fromOptions(options);
}
167196
function Email (template, options) {
	debug('email %s', template);

	options = options || {};

	if (!template) {
		throw new Error('You must provide an email template');
	}

	// init extension and engine
	// options.ext is supported for backwards compatibility with keystone.Email
	this.ext = path.extname(template) || options.ext;
	var engine = options.engine;
	if (!this.ext && !engine) {
		throw new Error('You must provide options.engine or include the extension in your template path');
	} else if (!this.ext && typeof engine === 'function') {
		throw new Error('You must include the extension in your template path when options.engine is a function');
	} else if (!this.ext) {
		this.ext = '.' + engine;
	} else if (!engine) {
		engine = this.ext.substr(1);
	}
	this.engine = getEngine(engine);
	if (typeof this.engine !== 'function') {
		throw new Error('Invalid engine (' + engine + ')');
	}
	// this corrects for if options.ext is passed in without the `.`
	if (this.ext[0] !== '.') {
		this.ext = '.' + this.ext;
	}

	// init template
	this.root = options.root || process.cwd();
	this.template = this.resolve(template);
	if (!isFile(this.template)) {
		throw new Error('Invalid template (' + template + '), could not find file "' + this.template + '"');
	}

	// init transport
	if (options.transport) {
		this.transport = getTransport(options.transport);
	}

	// stash options without consumed properties, this.send() uses it as defaults
	this.options = assign({}, options);
	delete this.options.engine;
	delete this.options.ext;
	delete this.options.root;
	delete this.options.transport;
}