public override void Send()
        {
            EmailMessage msg = new EmailMessage();
            foreach(string addr in AddressesFromList(To))
                msg.AddToAddress(addr);

            msg.FromAddress = new EmailAddress(From);
            msg.Subject = Subject;
            if(TextBody != null) msg.TextPart = new TextAttachment(TextBody);
            if(HtmlBody != null) msg.HtmlPart = new HtmlAttachment(HtmlBody);

            SmtpServer server = new SmtpServer(SmtpHost, SmtpServerPort);

            switch (SmtpAuthType)
            {
                case "BASIC":
                    log.Info("BASIC authentication was added to SMTP request");
                    SmtpAuthToken at = new SmtpAuthToken(SmtpAuthUsername, SmtpAuthPassword);
                    server.SmtpAuthToken = at;
                    break;
                default:
                    // no authentication
                    break;
            }

            log.Info(string.Format("Sending mail to {0} from {1} with subject {2}", msg.ToAddresses, msg.FromAddress, msg.Subject));
            msg.Send(server);
            log.Info("Sent mail");
        }
Esempio n. 2
0
        /// <summary>
        /// Sends an email with the specified parameters.
        /// </summary>
        /// <param name="to">Email address of the recipient.</param>
        /// <param name="from">Email address of the sender.</param>
        /// <param name="subject">Subject of the email.</param>
        /// <param name="message">The body of the email Message.</param>
        /// <returns></returns>
        public override bool Send(string to, string from, string subject, string message)
        {
            EmailMessage email = new EmailMessage();
            email.FromAddress = new EmailAddress(from);
            email.AddToAddress(new EmailAddress(to));
            email.Subject = subject;
            email.BodyText = message;

            SmtpServer smtpServer = new SmtpServer(SmtpServer, Port);

            //Authentication.
            if(this.UserName != null && this.Password != null)
            {
                smtpServer.SmtpAuthToken = new SmtpAuthToken(UserName, Password);
            }

            try
            {
                return email.Send(smtpServer);
            }
            //Mail Exception is thrown when there are network or connection errors
            catch(MailException mailEx)
            {
                string msg = String.Format("Connection or network error sending email from {0} to {1}", from, to);
                Log.Error(msg, mailEx);
            }
            //SmtpException is thrown for all SMTP exceptions
            catch (SmtpException smtpEx)
            {
                string msg = String.Format("Error sending email from {0} to {1}", from, to);
                Log.Error(msg, smtpEx);
            }
            return false;
        }
		public void TestSimpleSmtpNegotiation()
		{
			SmtpServer smtpserver=new SmtpServer("localhost");
			EmailMessage emailMessage=GetTestHtmlAndTextMessage();

			IMock mockSmtpProxy = new DynamicMock(typeof(ISmtpProxy));
			mockSmtpProxy.ExpectAndReturn("Open", new SmtpResponse(220, "welcome to the mock object server"), null);
			mockSmtpProxy.ExpectAndReturn("Helo", new SmtpResponse(250, "helo"), Dns.GetHostName());
			mockSmtpProxy.ExpectAndReturn("MailFrom", new SmtpResponse(250, "mail from"), emailMessage.FromAddress);
			foreach (EmailAddress rcpttoaddr in emailMessage.ToAddresses) 
			{
				mockSmtpProxy.ExpectAndReturn("RcptTo", new SmtpResponse(250, "receipt to"), rcpttoaddr);
			}
			mockSmtpProxy.ExpectAndReturn("Data", new SmtpResponse(354, "data open"), null);
			mockSmtpProxy.ExpectAndReturn("WriteData", new SmtpResponse(250, "data"), emailMessage.ToDataString());
			
			mockSmtpProxy.ExpectAndReturn("Quit", new SmtpResponse(221, "quit"), null);
			mockSmtpProxy.Expect("Close", null);

			ISmtpProxy smtpProxy= (ISmtpProxy) mockSmtpProxy.MockInstance;
			

			smtpserver.OverrideSmtpProxy(smtpProxy);

			
			emailMessage.Send(smtpserver);


		}
Esempio n. 4
0
 public SendRawThread(EmailAddress envelopefrom, EmailAddress[] mailto, String rawtext, SmtpServer smtpserver, LogWindow logwindow)
 {
     this._envelopefrom=envelopefrom;
     this._mailto=mailto;
     this._rawtext=rawtext;
     this._smtpserver=smtpserver;
     this._logwindow=logwindow;
 }
		public void TestSimpleSmtpNegotiationWithAuth()
		{


			SmtpServer smtpserver=new SmtpServer("localhost");
			smtpserver.SmtpAuthToken=new SmtpAuthToken("test", "test");			
			
			
			Base64Encoder encoder=Base64Encoder.GetInstance();
			String base64Username=encoder.EncodeString(smtpserver.SmtpAuthToken.UserName, System.Text.Encoding.ASCII );
			String base64Password=encoder.EncodeString(smtpserver.SmtpAuthToken.Password, System.Text.Encoding.ASCII );

			EmailMessage emailMessage=GetTestHtmlAndTextMessage();

			IMock mockSmtpProxy = new DynamicMock(typeof(ISmtpProxy));
			mockSmtpProxy.ExpectAndReturn("Open", new SmtpResponse(220, "welcome to the mock object server"), null);

			EhloSmtpResponse ehloResponse=new EhloSmtpResponse();
			ehloResponse.AddAvailableAuthType("login");
			
			ehloResponse.Message="OK";
			ehloResponse.ResponseCode=250;
			mockSmtpProxy.ExpectAndReturn("Ehlo",ehloResponse , Dns.GetHostName());
			mockSmtpProxy.ExpectAndReturn("Auth", new SmtpResponse(334, encoder.EncodeString("Username:"******"login");
			mockSmtpProxy.ExpectAndReturn("SendString", new SmtpResponse(334, encoder.EncodeString("Password:"******"SendString", new SmtpResponse(235, "Hooray, Authenticated"), base64Password);
			mockSmtpProxy.ExpectAndReturn("MailFrom", new SmtpResponse(250, "mail from"), emailMessage.FromAddress);
			foreach (EmailAddress rcpttoaddr in emailMessage.ToAddresses) 
			{
				mockSmtpProxy.ExpectAndReturn("RcptTo", new SmtpResponse(250, "receipt to"), rcpttoaddr);
			}
			mockSmtpProxy.ExpectAndReturn("Data", new SmtpResponse(354, "data open"), null);
			mockSmtpProxy.ExpectAndReturn("WriteData", new SmtpResponse(250, "data"), emailMessage.ToDataString());
			
			mockSmtpProxy.ExpectAndReturn("Quit", new SmtpResponse(221, "quit"), null);
			mockSmtpProxy.Expect("Close", null);

			ISmtpProxy smtpProxy= (ISmtpProxy) mockSmtpProxy.MockInstance;
			

			smtpserver.OverrideSmtpProxy(smtpProxy);
			
			try 
			{
				emailMessage.Send(smtpserver);
			}
			catch (SmtpException ex)
			{
				log.Debug("Exception was "+ex.Message);
				log.Debug(ex.StackTrace);
				throw ex;
			}

		}
Esempio n. 6
0
 /// <summary>
 /// Send the email via the specified SMTP server
 /// </summary>
 /// <param name="smtpserver">The SMTP server to use</param>
 /// <returns>true if the email was sent</returns>
 public bool Send(SmtpServer smtpserver)
 {
     // smtpproxy=SmtpProxy.GetInstance(smtpserver);
     if (_rcpttoaddresses.Count == 0)
     {
         throw new MailException("Please include a RCPT TO address");
     }
     if (_mailfrom == null)
     {
         throw new MailException("Please include a MAIL FROM address");
     }
     return(smtpserver.Send(this, _rcpttoaddresses, _mailfrom));
 }
Esempio n. 7
0
 public SendThread(
     EmailAddress fromaddress,
     EmailAddress[] toaddresses,
     EmailAddress envelopefrom,
     String subject,
     String htmlcontent,
     String textcontent,
     SmtpServer smtpserver,
     LogWindow logwindow)
 {
     _fromaddress=fromaddress;
     _toaddresses=toaddresses;
     _envelopefrom=envelopefrom;
     _subject=subject;
     _htmlcontent=htmlcontent;
     _textcontent=textcontent;
     _smtpserver=smtpserver;
     _logwindow=logwindow;
 }
Esempio n. 8
0
        /// <summary>
        /// Send out the email via the smtp server given.  If
        /// the SMTP server throws an error, an SmtpException will
        /// be thrown.  All other exceptions will be MailExceptions
        /// </summary>
        /// <param name="smtpserver">The outgoing SMTP server.</param>
        /// <returns>true if sent successfully.  (note that this
        /// will not currently return false, but in the future
        /// a false value may be used)</returns>
        public bool Send(SmtpServer smtpserver)
        {
            //SmtpProxy smtpproxy=smtpserver.GetSmtpProxy();
            if (_fromaddress == null)
            {
                throw new MailException(ARM.GetInstance().GetString("error_no_from"));
            }

            EmailAddress envelopefrom = _envelopefromaddress;

            if (envelopefrom == null)
            {
                envelopefrom = _fromaddress;
            }
            EmailAddressCollection allrecipients = new EmailAddressCollection();

            allrecipients.AddCollection(_toaddresses);
            allrecipients.AddCollection(_ccaddresses);
            allrecipients.AddCollection(_bccaddresses);
            return(smtpserver.Send(this, allrecipients, envelopefrom));
        }
Esempio n. 9
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                m_log.Error("[EMAIL] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                if (!m_localOnly)
                {
                    string m_ObjectRegionName;
                    SceneObjectPart part = findPrim(objectID, out m_ObjectRegionName);
                    if (part != null)
                    {
                        lock (m_Scenes)
                        {
                            foreach (Scene s in m_Scenes.Values)
                            {
                                ScenePresence SP = s.GetScenePresence(part.OwnerID);
                                if (SP != null)
                                {
                                    if (!SP.IsChildAgent)
                                        SP.ControllingClient.SendAlertMessage("llEmail: email module not configured for outgoing emails");
                                }
                            }
                        }
                    }
                }
                // regular email, send it out
                try
                {
                    //Creation EmailMessage
                    EmailMessage emailMessage = new EmailMessage();
                    //From
                    emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                    //To - Only One
                    emailMessage.AddToAddress(new EmailAddress(address));
                    //Subject
                    emailMessage.Subject = subject;
                    //TEXT Body
                    resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                    emailMessage.BodyText = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                    //Config SMTP Server
                    //Set SMTP SERVER config
                    SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
                    // Add authentication only when requested
                    //
                    if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                    {
                        //Authentication
                        smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                    }
                    //Send Email Message
                    emailMessage.Send(smtpServer);

                    //Log
                    m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
                }
                catch (Exception e)
                {
                    m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                }
            }
            else
            {
                // inter object email, keep it in the family
                Email email = new Email();
                email.time = ((int)((DateTime.UtcNow - new DateTime(1970,1,1,0,0,0)).TotalSeconds)).ToString();
                email.subject = subject;
                email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
                email.message = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                string guid = address.Substring(0, address.IndexOf("@"));
                UUID toID = new UUID(guid);

                if (IsLocal(toID))
                {
                    // object in this region
                    InsertEmail(toID, email);
                }
                else
                {
                    // object on another region

                    //This should be dealt with by other modules, not us
                }
            }

            //DONE: Message as Second Life style
            //20 second delay - AntiSpam System - for now only 10 seconds
            DelayInSeconds(10);
        }
Esempio n. 10
0
		public static void SendMail(umbraco.cms.businesslogic.member.MemberGroup Group, umbraco.cms.businesslogic.property.Property Property, string fromName, string fromEmail, bool IsHtml) 
		{
            // Create ArrayList with emails who've received the e-mail
            ArrayList sent = new ArrayList();

			// set timeout
			System.Web.HttpContext.Current.Server.ScriptTimeout = 43200; // 12 hours
			// version
			string version = Property.VersionId.ToString();

			// Get document
			umbraco.cms.businesslogic.web.Document d = new umbraco.cms.businesslogic.web.Document(umbraco.cms.businesslogic.Content.GetContentFromVersion(Property.VersionId).Id);
			int id = d.Id;
			System.Web.HttpContext.Current.Items["pageID"] = id;

			// Format mail
			string subject = d.Text;
			string sender = "\"" + fromName + "\" <" + fromEmail + ">";

			// Get template			
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			System.IO.StringWriter sw = new StringWriter(sb);
			System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(sw);
			umbraco.template t = new template(d.Template);
			t.ParseWithControls(new umbraco.page(d.Id, d.Version)).RenderControl(writer);


			EmailMessage message = mailerHelper.CreateEmbeddedEmail(sb.ToString(), Cms.BusinessLogic.web.Document.GetContentFromVersion(Property.VersionId).Id);
            			
			message.FromAddress = new EmailAddress(fromEmail, fromName);
			message.Subject = subject;
			SmtpServer smtpServer = new SmtpServer(GlobalSettings.SmtpServer);

			// Bulk send mails
			int counter = 0;
			System.Text.StringBuilder sbStatus = new System.Text.StringBuilder();
			sbStatus.Append("The Newsletter '" + d.Text + "' was starting at " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "\n");
			using(SqlDataReader dr = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(umbraco.GlobalSettings.DbDSN, CommandType.Text, "select text, email from cmsMember inner join umbracoNode node on node.id = cmsMember.nodeId inner join cmsMember2memberGroup on cmsmember.nodeId = cmsMember2MemberGroup.member where memberGroup = @memberGroupId", new SqlParameter("@memberGroupId", Group.Id)))
			{
				while(dr.Read())
				{
					try
					{
                        if (!sent.Contains(dr["email"].ToString()))
                        {
                            message.ToAddresses.Clear();
                            message.ToAddresses.Add(new EmailAddress(dr["email"].ToString(), dr["text"].ToString()));
                            message.Send(smtpServer);

                            // add to arraylist of receiptients
                            sent.Add(dr["email"].ToString());

                            // Append to status
                            sbStatus.Append("Sent to " + dr["text"].ToString() + " <" + dr["email"].ToString() + "> \n\r");
                        }
                        else
                        {
                            // Append to status
                            sbStatus.Append("E-mail has already been sent to email '" + dr["email"].ToString() + ". You have a duplicate member: " + dr["text"].ToString() + " <" + dr["email"].ToString() + "> \n\r");
                        }
					}
					catch(Exception ee)
					{
						sbStatus.Append("Error sending to " + dr["text"].ToString() + " <" + dr["email"].ToString() + ">: " +
						                ee.ToString() + " \n");
					}

					// For progress bar
					counter++;

					if(counter % 5 == 0)
					{
						System.Web.HttpContext.Current.Application.Lock();
						System.Web.HttpContext.Current.Application["ultraSimpleMailerProgress" + id.ToString() + "Done"] = counter;
						System.Web.HttpContext.Current.Application.UnLock();
					}
				}
			}

			sbStatus.Append("Finished at " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "\n");

			// Send status mail
			library.SendMail(fromEmail, fromEmail, "Newsletter status", sbStatus.ToString(), false);
		}
Esempio n. 11
0
        private String SubstituteVariables(String str, SmtpServer smtpserver)
        {
            str=str.Replace("${TEST_NUMBER}", _testNumber.ToString());
            str=str.Replace("${SENDER_HOST}", Dns.GetHostName());
            str=str.Replace("${SMTP_HOST}", smtpserver.ToString());
            str=str.Replace("${LOCAL_TIME}", DateTime.Now.ToString());

            return str;
        }
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;
            string[] host = address.Split('@');
            string hostcheck = host[1];
            WebClient client = new WebClient();
            value = client.DownloadString("http://osxchange.org/router.php?grid=" + hostcheck);
            // string routeraddress = address.en
            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[OpenSimEmail] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                m_log.Error("[OpenSimEmail] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
            if (value != "false" && !address.EndsWith(m_InterObjectHostname))
            {
                m_log.Info(value);
                Hashtable ReqHash = new Hashtable();
                ReqHash["fromaddress"] = objectID.ToString() + "@" + m_HostName;
                ReqHash["toaddress"] = address.ToString();
                ReqHash["timestamp"] = ConvertToUnixTimestamp(DateTime.UtcNow);
                ReqHash["subject"] = subject.ToString();
                ReqHash["objectname"] = LastObjectName;
                ReqHash["position"] = LastObjectPosition;
                ReqHash["region"] = LastObjectRegionName;
                ReqHash["messagebody"] = body.ToString();

                Hashtable result = GenericXMLRPCRequestRemote(ReqHash,
                        "send_email");
                m_log.Error("Address not match intern mail" + address);
                if (!Convert.ToBoolean(result["success"]))
                {
                    return;
                }
                DelayInSeconds(20);

            }




            else if (!address.EndsWith(m_InterObjectHostname))
            {
                // regular email, send it out

                //Creation EmailMessage
                EmailMessage emailMessage = new EmailMessage();
                //From
                emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                //To - Only One
                emailMessage.AddToAddress(new EmailAddress(address));
                //Subject
                emailMessage.Subject = subject;
                //TEXT Body
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                          "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                          LastObjectPosition + "\n\n" + body;

                //Config SMTP Server
                //Set SMTP SERVER config
                SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                // Add authentication only when requested
                //
                if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                {
                    //Authentication
                    smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                }
                //Send Email Message
                emailMessage.Send(smtpServer);

                //Log
                m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);


            }
            else if (address.EndsWith(m_InterObjectHostname))
            {
                Hashtable ReqHash = new Hashtable();
                ReqHash["fromaddress"] = objectID.ToString() + "@" + m_HostName;
                ReqHash["toaddress"] = address.ToString();
                ReqHash["timestamp"] = ConvertToUnixTimestamp(DateTime.UtcNow);
                ReqHash["subject"] = subject.ToString();
                ReqHash["objectname"] = LastObjectName;
                ReqHash["position"] = LastObjectPosition;
                ReqHash["region"] = LastObjectRegionName;
                ReqHash["messagebody"] = body.ToString();
                m_log.Error("Address is internal" + address);
                Hashtable result = GenericXMLRPCRequest(ReqHash,
                        "send_email");

                if (!Convert.ToBoolean(result["success"]))
                {
                    return;
                }
                DelayInSeconds(20);
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Get an instance of the SMTP Proxy
 /// </summary>
 /// <param name="smtpserver"></param>
 /// <returns></returns>
 public static SmtpProxy GetInstance(SmtpServer smtpserver)
 {
     return(new SmtpProxy(smtpserver));
 }
Esempio n. 14
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            try
            {
                //Creation EmailMessage
                EmailMessage emailMessage = new EmailMessage();
                //From
                emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                //To - Only One
                emailMessage.AddToAddress(new EmailAddress(address));
                //Subject
                emailMessage.Subject = subject;
                //TEXT Body
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                            "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                            LastObjectPosition + "\n\n" + body;

                int len = emailMessage.BodyText.Length;
                if ((address.Length + subject.Length + len) > 4096)
                {
                    len -= address.Length;
                    len -= subject.Length;
                    emailMessage.BodyText = emailMessage.BodyText.Substring(0, len);
                }

                //Config SMTP Server
                //Set SMTP SERVER config
                SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
                // Add authentication only when requested
                //
                if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                {
                    //Authentication
                    smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                }
                //Send Email Message
                emailMessage.Send(smtpServer);

                //Log
                m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
            }
            catch (Exception e)
            {
                m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Send out the email via the smtp server given.  If 
        /// the SMTP server throws an error, an SmtpException will
        /// be thrown.  All other exceptions will be MailExceptions
        /// </summary>
        /// <param name="smtpserver">The outgoing SMTP server.</param>
        /// <returns>true if sent successfully.  (note that this
        /// will not currently return false, but in the future
        /// a false value may be used)</returns>
        public bool Send(SmtpServer smtpserver)
        {
            //SmtpProxy smtpproxy=smtpserver.GetSmtpProxy();
            if(_fromaddress == null)
            {
                throw new MailException(ARM.GetInstance().GetString("error_no_from"));
            }

            EmailAddress envelopefrom=_envelopefromaddress;
            if (envelopefrom==null)
            {
                envelopefrom=_fromaddress;
            }
            EmailAddressCollection allrecipients=new EmailAddressCollection();
            allrecipients.AddCollection(_toaddresses);
            allrecipients.AddCollection(_ccaddresses);
            allrecipients.AddCollection(_bccaddresses);
            return smtpserver.Send(this, allrecipients, envelopefrom);
        }
		public void TestFailedSmtpNegotiationWithAuth()
		{


			SmtpServer smtpserver=new SmtpServer("localhost");
			smtpserver.SmtpAuthToken=new SmtpAuthToken("test", "test");			
			
			
			Base64Encoder encoder=Base64Encoder.GetInstance();
			String base64Username=encoder.EncodeString(smtpserver.SmtpAuthToken.UserName, System.Text.Encoding.ASCII );
			String base64Password=encoder.EncodeString(smtpserver.SmtpAuthToken.Password, System.Text.Encoding.ASCII );

			EmailMessage emailMessage=GetTestHtmlAndTextMessage();

			IMock mockSmtpProxy = new DynamicMock(typeof(ISmtpProxy));
			mockSmtpProxy.ExpectAndReturn("Open", new SmtpResponse(220, "welcome to the mock object server"), null);

			EhloSmtpResponse ehloResponse=new EhloSmtpResponse();
			ehloResponse.AddAvailableAuthType("login");
			
			ehloResponse.Message="OK";
			ehloResponse.ResponseCode=250;
			mockSmtpProxy.ExpectAndReturn("Ehlo", ehloResponse , Dns.GetHostName());
			mockSmtpProxy.ExpectAndReturn("Auth", new SmtpResponse(554, "Unrecognized auth type"), "login");

			ISmtpProxy smtpProxy= (ISmtpProxy) mockSmtpProxy.MockInstance;

			smtpserver.OverrideSmtpProxy(smtpProxy);

			/*
			mockSmtpProxy.ExpectAndReturn("SendString", new SmtpResponse(554, "Invalid UserName"), base64Username);
			mockSmtpProxy.ExpectAndReturn("SendString", new SmtpResponse(554, "Invalid Password"), base64Password);
			mockSmtpProxy.ExpectAndReturn("MailFrom", new SmtpResponse(250, "mail from"), emailMessage.FromAddress);
			foreach (EmailAddress rcpttoaddr in emailMessage.ToAddresses) 
			{
				mockSmtpProxy.ExpectAndReturn("RcptTo", new SmtpResponse(250, "receipt to"), rcpttoaddr);
			}
			mockSmtpProxy.ExpectAndReturn("Data", new SmtpResponse(354, "data open"), null);
			mockSmtpProxy.ExpectAndReturn("WriteData", new SmtpResponse(250, "data"), emailMessage.ToDataString());
			
			mockSmtpProxy.ExpectAndReturn("Quit", new SmtpResponse(221, "quit"), null);
			mockSmtpProxy.Expect("Close", null);
			*/

			try 
			{
				emailMessage.Send(smtpserver);
				Assert.Fail("The auth type is wrong");
			}
			catch (SmtpException ex)
			{
				log.Debug("ERROR CODE IS "+554);
				Assert.AreEqual(554,ex.ErrorCode);
			}



		}
Esempio n. 17
0
 /// <summary>
 /// Send the email via the specified SMTP server
 /// </summary>
 /// <param name="smtpserver">The SMTP server to use</param>
 /// <returns>true if the email was sent</returns>
 public bool Send(SmtpServer smtpserver)
 {
     // smtpproxy=SmtpProxy.GetInstance(smtpserver);
     if (_rcpttoaddresses.Count==0)
     {
         throw new MailException("Please include a RCPT TO address");
     }
     if (_mailfrom==null)
     {
         throw new MailException("Please include a MAIL FROM address");
     }
     return smtpserver.Send(this, _rcpttoaddresses, _mailfrom);
 }
		public void SetUp() 
		{
			_smtpserver=TestAddressHelper.GetSmtpServer();
		}
Esempio n. 19
0
        /// <summary>
        ///     SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="scene">Can be null</param>
        public void SendEmail(UUID objectID, string address, string subject, string body, IScene scene)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            const string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                              + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                              + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                              + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                              + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                MainConsole.Instance.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > m_MaxEmailSize)
            {
                MainConsole.Instance.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            if (scene != null)
                resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition,
                                              out LastObjectRegionName, scene);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // regular email, send it out
                    try
                    {
                        //Creation EmailMessage

                        string fromEmailAddress;

                        if (scene != null && objectID != UUID.Zero)
                            fromEmailAddress = objectID.ToString() + "@" + m_HostName;
                        else
                            fromEmailAddress = "no-reply@" + m_HostName;

                        EmailMessage emailMessage = new EmailMessage
                                                        {
                                                            FromAddress =
                                                                new EmailAddress(fromEmailAddress),
                                                            Subject = subject
                                                        };

                        //To - Only One
                        emailMessage.AddToAddress(new EmailAddress(address));
                        //Text
                        emailMessage.BodyText = body;
                        if (scene != null)
                        {
                            // If Object Null Dont Include Object Info Headers (Offline IMs)
                            if(objectID != UUID.Zero)
                                emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                                        "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                        LastObjectPosition + "\n\n";

                            emailMessage.BodyText += emailMessage.BodyText;
                        }

                        //Config SMTP Server
                        //Set SMTP SERVER config
                        SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                        // Add authentication only when requested
                        if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                            smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                        //Add timeout of 15 seconds
                        smtpServer.ServerTimeout = 15000;
                        //Send Email Message
                        didError = !emailMessage.Send(smtpServer);

                        //Log
                        if (!didError)
                            MainConsole.Instance.Info("[EMAIL] EMail sent to: " + address + " from object: " +
                                                      fromEmailAddress);
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                        didError = true;
                    }
                }
                if (((didError) || (m_localOnly)) && (scene != null))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName, scene);
                    if (part != null)
                    {
                        IScenePresence sp = scene.GetScenePresence(part.OwnerID);
                        if ((sp != null) && (!sp.IsChildAgent))
                        {
                            sp.ControllingClient.SendAlertMessage(
                                "llEmail: email module not configured for outgoing emails");
                        }
                    }
                }
            }
            else
            {
                // inter object email, keep it in the family
                string guid = address.Substring(0, address.IndexOf("@", StringComparison.Ordinal));
                UUID toID = new UUID(guid);

                if (IsLocal(toID, scene))
                {
                    // object in this region
                    InsertEmail(toID, new Email
                                          {
                                              time =
                                                  ((int)
                                                   ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds))
                                                  .
                                                  ToString(CultureInfo.InvariantCulture),
                                              subject = subject,
                                              sender = objectID.ToString() + "@" + m_InterObjectHostname,
                                              message = "Object-Name: " + LastObjectName +
                                                        "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                        LastObjectPosition + "\n\n" + body,
                                              toPrimID = toID
                                          });
                }
                else
                {
                    // object on another region

                    Email email = new Email
                                      {
                                          time =
                                              ((int)
                                               ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                                              ToString(CultureInfo.InvariantCulture),
                                          subject = subject,
                                          sender = objectID.ToString() + "@" + m_InterObjectHostname,
                                          message = body,
                                          toPrimID = toID
                                      };
                    IEmailConnector conn = Framework.Utilities.DataManager.RequestPlugin<IEmailConnector>();
                    conn.InsertEmail(email);
                }
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Get an instance of the SMTP Proxy
 /// </summary>
 /// <param name="smtpserver"></param>
 /// <returns></returns>
 public static SmtpProxy GetInstance(SmtpServer smtpserver)
 {
     return new SmtpProxy(smtpserver);
 }
Esempio n. 21
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
                return;
            }
            if ((subject.Length + body.Length) > m_MaxEmailSize)
            {
                m_log.Error("[EMAIL] subject + body larger than limit of " + m_MaxEmailSize + " bytes");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                // regular email, send it out
                try
                {
                    //Creation EmailMessage
                    EmailMessage emailMessage = new EmailMessage();
                    //From
                    emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                    //To - Only One
                    emailMessage.AddToAddress(new EmailAddress(address));
                    //Subject
                    emailMessage.Subject = subject;
                    //TEXT Body
                    resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                    emailMessage.BodyText = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                    //Config SMTP Server
                    //Set SMTP SERVER config
                    SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
                    // Add authentication only when requested
                    //
                    if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                    {
                        //Authentication
                        smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                    }
                    //Send Email Message
                    emailMessage.Send(smtpServer);

                    //Log
                    m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
                }
                catch (Exception e)
                {
                    m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                }
            }
            else
            {
                // inter object email, keep it in the family
                Email email = new Email();
                email.time = ((int)((DateTime.UtcNow - new DateTime(1970,1,1,0,0,0)).TotalSeconds)).ToString();
                email.subject = subject;
                email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
                email.message = "Object-Name: " + LastObjectName +
                              "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                              LastObjectPosition + "\n\n" + body;

                string guid = address.Substring(0, address.IndexOf("@"));
                UUID toID = new UUID(guid);

                if (IsLocal(toID)) // TODO FIX check to see if it is local
                {
                    // object in this region
                    InsertEmail(toID, email);
                }
                else
                {
                    // object on another region
                    // TODO FIX
                }
            }
        }
Esempio n. 22
0
        //private StringBuilder _conversation=new StringBuilder();
        //private IPEndPoint _iEndPoint=null;

        /*
         #region SmtpProxy
         * private  SmtpProxy(System.Net.IPAddress ipaddress, int portno)
         * {
         *      _iendpoint = new IPEndPoint (ipaddress, portno);
         * }
         #endregion
         */

        #region SmtpProxy
        private SmtpProxy(SmtpServer smtpserver)
        {
            _smtpserver = smtpserver;
        }
Esempio n. 23
0
        /// <summary>
        ///   SendMail function utilized by llEMail
        /// </summary>
        /// <param name = "objectID"></param>
        /// <param name = "address"></param>
        /// <param name = "subject"></param>
        /// <param name = "body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
                return;

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                        + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                        + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                        + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                        + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict = new Regex(EMailpatternStrict);
            bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
            if (!isEMailStrictMatch)
            {
                MainConsole.Instance.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                MainConsole.Instance.Error("[EMAIL] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName = string.Empty;
            string LastObjectPosition = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                bool didError = false;
                if (!m_localOnly)
                {
                    // regular email, send it out
                    try
                    {
                        //Creation EmailMessage
                        EmailMessage emailMessage = new EmailMessage
                                                        {
                                                            FromAddress =
                                                                new EmailAddress(objectID.ToString() + "@" + m_HostName)
                                                        };
                        //From
                        //To - Only One
                        emailMessage.AddToAddress(new EmailAddress(address));
                        //Subject
                        emailMessage.Subject = subject;
                        //Text
                        emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                                "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                LastObjectPosition + "\n\n" + body;

                        //Config SMTP Server
                        //Set SMTP SERVER config
                        SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                        // Add authentication only when requested
                        if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                            smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                        //Add timeout of 15 seconds
                        smtpServer.ServerTimeout = 15000;
                        //Send Email Message
                        didError = !emailMessage.Send(smtpServer);

                        //Log
                        if (!didError)
                            MainConsole.Instance.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() +
                                       "@" + m_HostName);
                    }
                    catch (Exception e)
                    {
                        MainConsole.Instance.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                        didError = true;
                    }
                }
                if ((didError) || (m_localOnly))
                {
                    // Notify Owner
                    ISceneChildEntity part = findPrim(objectID, out LastObjectRegionName);
                    if (part != null)
                    {
                        lock (m_Scenes)
                        {
#if (!ISWIN)
                            foreach (IScene s in m_Scenes.Values)
                            {
                                IScenePresence SP = s.GetScenePresence(part.OwnerID);
                                if ((SP != null) && (!SP.IsChildAgent))
                                {
                                    SP.ControllingClient.SendAlertMessage("llEmail: email module not configured for outgoing emails");
                                }
                            }
#else
                            foreach (IScenePresence SP in m_Scenes.Values.Select(s => s.GetScenePresence(part.OwnerID)).Where(SP => (SP != null) && (!SP.IsChildAgent)))
                            {
                                SP.ControllingClient.SendAlertMessage(
                                    "llEmail: email module not configured for outgoing emails");
                            }
#endif
                        }
                    }
                }
            }
            else
            {
                // inter object email, keep it in the family
                string guid = address.Substring(0, address.IndexOf("@"));
                UUID toID = new UUID(guid);

                if (IsLocal(toID))
                {
                    // object in this region
                    InsertEmail(toID, new Email
                                  {
                                      time =
                                          ((int) ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                                          ToString(),
                                      subject = subject,
                                      sender = objectID.ToString() + "@" + m_InterObjectHostname,
                                      message = "Object-Name: " + LastObjectName +
                                                "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                                LastObjectPosition + "\n\n" + body,
                                      toPrimID = toID
                                  });
                }
                else
                {
                    // object on another region

                    Email email = new Email
                    {
                        time =
                            ((int)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).
                            ToString(),
                        subject = subject,
                        sender = objectID.ToString() + "@" + m_InterObjectHostname,
                        message = body,
                        toPrimID = toID
                    };
                    Aurora.Framework.IEmailConnector conn = Aurora.DataManager.DataManager.RequestPlugin<Aurora.Framework.IEmailConnector>();
                    conn.InsertEmail(email);
                }
            }
        }
Esempio n. 24
0
 private SmtpProxy(SmtpServer smtpserver)
 {
     _smtpserver=smtpserver;
 }