Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            // Create attendees of the meeting
            MailAddressCollection attendees = new MailAddressCollection();
            attendees.Add("*****@*****.**");
            attendees.Add("*****@*****.**");

            // Set up appointment
            Appointment app = new Appointment(
                "Location", // location of meeting
                DateTime.Now, // start date
                DateTime.Now.AddHours(1), // end date
                new MailAddress("*****@*****.**"), // organizer
                attendees); // attendees

            // Set up message that needs to be sent
            MailMessage msg = new MailMessage();
            msg.From = "*****@*****.**";
            msg.To = "*****@*****.**";
            msg.Subject = "appointment request";
            msg.Body = "you are invited";

            // Add meeting request to the message
            msg.AddAlternateView(app.RequestApointment());

            // Set up the SMTP client to send email with meeting request
            SmtpClient client = new SmtpClient("host", 25, "user", "password");
            client.Send(msg);
        }
        public void SendAnEmail()
        {
            try
            {
                MailMessage _message = new MailMessage();
                SmtpClient _smptClient = new SmtpClient();

                _message.Subject = _emailSubject;

                _message.Body = _emailBody;

                MailAddress _mailFrom = new MailAddress(_emailFrom,_emailFromFriendlyName);
            
                MailAddressCollection _mailTo = new MailAddressCollection();
                _mailTo.Add(_emailTo);

                _message.From = _mailFrom;
                _message.To.Add(new MailAddress(_emailTo,_emailToFriendlyName));

                System.Net.NetworkCredential _crens = new System.Net.NetworkCredential(
                    _smtpHostUserName,_smtpHostPassword);
                _smptClient.Host = _smtpHost;
                _smptClient.Credentials = _crens;


                _smptClient.Send(_message);
            }
            catch (Exception er)
            {
                Log("C:\\temp\\", "Error.log", er.ToString());
            }
        }
Ejemplo n.º 3
0
        public static void Send(MailAddress from, MailAddress replyTo, MailAddress to, string subject, string body)
        {
            MailAddressCollection toList = new MailAddressCollection();
            toList.Add(to);

            Send(from, replyTo, toList, subject, body);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Adds the mails to the address-collection.
 /// </summary>
 /// <param name="collection">The collection.</param>
 /// <param name="addresses">The addresses.</param>
 private void AddMailsToCollection(MailAddressCollection collection, IEnumerable<string> addresses)
 {
     foreach (string address in addresses)
     {
         collection.Add(new MailAddress(address));
     }
 }
Ejemplo n.º 5
0
 public void CopyToMailAddressCollection(Rebex.Mime.Headers.MailAddressCollection rmac, MailAddressCollection mac)
 {
     foreach (Rebex.Mime.Headers.MailAddress rma in rmac)
     {
         mac.Add(ToMailAddress(rma));
     }
 }
Ejemplo n.º 6
0
		/// <summary>
		/// Send a plain text email with the specified properties. The email will appear to come from the name and email specified in the
		/// EmailFromName and EmailFromAddress configuration settings. If the emailRecipient parameter is not specified, the email
		/// is sent to the address configured in the emailToAddress setting in the configuration file. The e-mail is sent on a 
		/// background thread, so if an error occurs on that thread no exception bubbles to the caller (the error, however, is
		/// recorded in the error log). If it is important to know if the e-mail was successfully sent, use the overload of this
		/// method that specifies a sendOnBackgroundThread parameter.
		/// </summary>
		/// <param name="emailRecipient">The recipient of the email.</param>
		/// <param name="subject">The text to appear in the subject of the email.</param>
		/// <param name="body">The body of the email. If the body is HTML, specify true for the isBodyHtml parameter.</param>
		public static void SendEmail(MailAddress emailRecipient, string subject, string body)
		{
			MailAddressCollection mailAddresses = new MailAddressCollection();
			mailAddresses.Add(emailRecipient);

			SendEmail(mailAddresses, subject, body, false, true);
		}
Ejemplo n.º 7
0
        internal override MailAddress[] ParseAddressList(string list)
        {
            List<MailAddress> mails = new List<MailAddress>();

            if (string.IsNullOrEmpty(list))
                return mails.ToArray();

            foreach (string part in SplitAddressList(list))
            {
                MailAddressCollection mcol = new MailAddressCollection();
                try
                {
                    // .NET won't accept address-lists ending with a ';' or a ',' character, see #68.
                    mcol.Add(part.TrimEnd(';', ','));
                    foreach (MailAddress m in mcol)
                    {
                        // We might still need to decode the display name if it is Q-encoded.
                        string displayName = Util.DecodeWords(m.DisplayName);
                        mails.Add(new MailAddress(m.Address, displayName));
                    }
                }
                catch
                {
                    // We don't want this to throw any exceptions even if the entry is malformed.
                }
            }
            return mails.ToArray();
        }
        public static void Run()
        {
            // ExStart:GetMailTips
            // Create instance of EWSClient class by giving credentials
            IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
            Console.WriteLine("Connected to Exchange server...");
            // Provide mail tips options
            MailAddressCollection addrColl = new MailAddressCollection();
            addrColl.Add(new MailAddress("*****@*****.**", true));
            addrColl.Add(new MailAddress("*****@*****.**", true));
            GetMailTipsOptions options = new GetMailTipsOptions("*****@*****.**", addrColl, MailTipsType.All);

            // Get Mail Tips
            MailTips[] tips = client.GetMailTips(options);

            // Display information about each Mail Tip
            foreach (MailTips tip in tips)
            {
                // Display Out of office message, if present
                if (tip.OutOfOffice != null)
                {
                    Console.WriteLine("Out of office: " + tip.OutOfOffice.ReplyBody.Message);
                }

                // Display the invalid email address in recipient, if present
                if (tip.InvalidRecipient == true)
                {
                    Console.WriteLine("The recipient address is invalid: " + tip.RecipientAddress);
                }
            }
            // ExEnd:GetMailTips
        }
Ejemplo n.º 9
0
 public void SendEmail(MailAddress from, MailAddressCollection to, MailAddressCollection cc, MailAddressCollection bcc, string subj, string body)
 {
     MailMessage msg = new MailMessage();
     foreach(MailAddress item in to)
     {
         msg.To.Add(item);
     }
     foreach (MailAddress item in cc)
     {
         msg.CC.Add(item);
     }
     foreach (MailAddress item in bcc)
     {
         msg.Bcc.Add(item);
     }
     msg.From = from;
     msg.Sender = from;
     Log.Info("Preparing message FROM " + from.DisplayName + " at address " + from.Address);
     msg.Subject = subj;
     msg.Body = body;
     Log.Info("Sending email message...");
     try
     {
         tseClient.Send(msg);
     }
     catch (Exception)
     {
         throw;
     }
 }
Ejemplo n.º 10
0
 private void Populate(MailAddressCollection dest, IEnumerable<string> source)
 {
     foreach (string mail in source)
     {
         dest.Add(FromString(mail));
     }
 }
        public void SendAnEmail()
        {
            bool _success = false;
            try
            {
                MailMessage _message = new MailMessage();
                SmtpClient _smptClient = new SmtpClient();

                _message.Subject = _emailSubject;

                _message.Body = _emailBody;

                MailAddress _mailFrom = new MailAddress(_emailFrom,_emailFromFriendlyName);
            
                MailAddressCollection _mailTo = new MailAddressCollection();
                _mailTo.Add(_emailTo);

                _message.From = _mailFrom;
                _message.To.Add(new MailAddress(_emailTo,_emailToFriendlyName));

                System.Net.NetworkCredential _crens = new System.Net.NetworkCredential(
                    _smtpHostUserName,_smtpHostPassword);
                _smptClient.Host = _smtpHost;
                _smptClient.Credentials = _crens;


                _smptClient.Send(_message);
            }
            catch (Exception er)
            {
                string s1 = er.Message;
            }
        }
Ejemplo n.º 12
0
        public static void SendMail(string FromName, string Subject, string Body, MailAddressCollection addresses)
        {
            System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
            for (int i = 0; i < addresses.Count; i++) {
                email.To.Add(addresses[i]);
            }

            email.From = new MailAddress(ConfigurationManager.AppSettings["FromEmail"], FromName);
            email.Subject = Subject;

            email.Body = Body;
            email.IsBodyHtml = true;
            email.Priority = MailPriority.Normal;
            email.BodyEncoding = System.Text.Encoding.UTF8;
            SmtpClient mailClient = new System.Net.Mail.SmtpClient();
            mailClient.Timeout = 400000;
            mailClient.EnableSsl = false;

            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            NetworkCredential basicAuthenticationInfo =
                new NetworkCredential("*****@*****.**", "147258");
            mailClient.Host = "mail.dbhsoft.com";
            mailClient.Credentials = basicAuthenticationInfo;
            mailClient.Port = 587;

            try {
                mailClient.Send(email);
            } catch (Exception) {
                throw;
            }
        }
Ejemplo n.º 13
0
 public static void Enviar(MailAddress to, String body, String subject, List<Attachment> attachments)
 {
     MailAddressCollection emails = new MailAddressCollection();
     emails.Add(to);
     MailAddress from = Util.Email.EmailEnvioPadrao;
     Enviar(from, emails, body, subject, attachments);
 }
        /// <summary>
        /// Applies the override to a MailAddressCollection
        /// </summary>
        /// <param name="addresses">The addresses.</param>
        /// <returns></returns>
        protected MailAddressCollection ApplyMailAddressOverride(MailAddressCollection addresses)
        {
            if (clear)
            {
                addresses.Clear();
            }
            else
            {
                if (!string.IsNullOrEmpty(overrideString))
                {
                    addresses.Clear();
                    addresses.Add(overrideString);
                }

                if (!string.IsNullOrEmpty(prependString))
                {
                    var old = addresses.ToString();
                    addresses.Clear();
                    addresses.Add(prependString);
                    if(!string.IsNullOrWhiteSpace(old)) addresses.Add(old);
                }

                if (!string.IsNullOrEmpty(appendString))
                {
                    addresses.Add(appendString);
                }
            }

            return addresses;
        }
		private void CreateMailMessage(DeliveryInfo deliveryInfo, MailMessage message)
		{
			var recipients = deliveryInfo.To;
			if (string.IsNullOrEmpty(recipients)) throw new ArgumentNullException(recipients);

			var addressCollection = new MailAddressCollection();

			if (!MailSettings.UseEmailTestMode) addressCollection.Add(recipients);
			else addressCollection.Add(MailSettings.TestEmailAddress);

			foreach (var address in addressCollection)
			{
				message.To.Add(EmailHelper.FixMailAddressDisplayName(address, MailSettings.EmailHeaderEncoding));
			}

			message.From = EmailHelper.FixMailAddressDisplayName(new MailAddress(deliveryInfo.From), MailSettings.EmailHeaderEncoding);

			message.BodyEncoding = Encoding.GetEncoding(MailSettings.EmailBodyEncoding);
			message.SubjectEncoding = Encoding.GetEncoding(MailSettings.EmailSubjectEncoding);
			message.HeadersEncoding = Encoding.GetEncoding(MailSettings.EmailHeaderEncoding);

			message.Body = deliveryInfo.Body;
			message.IsBodyHtml = deliveryInfo.IsBodyHtml;
			message.Subject = deliveryInfo.Subject;

			if (!string.IsNullOrEmpty(deliveryInfo.ReplyTo))
			{
				var replyToCollection = new MailAddressCollection { deliveryInfo.ReplyTo };

				foreach (var address in replyToCollection)
				{
					message.ReplyToList.Add(EmailHelper.FixMailAddressDisplayName(address, MailSettings.EmailHeaderEncoding));
				}
			}
		}
 internal SendMailAsyncResult(SmtpConnection connection, string from, MailAddressCollection toCollection, string deliveryNotify, AsyncCallback callback, object state) : base(null, state, callback)
 {
     this.failedRecipientExceptions = new ArrayList();
     this.toCollection = toCollection;
     this.connection = connection;
     this.from = from;
     this.deliveryNotify = deliveryNotify;
 }
Ejemplo n.º 17
0
 private static void PopulateAddresses(string recipients, MailAddressCollection collection)
 {
     if (string.IsNullOrEmpty(recipients)) return;
     if (collection == null) return;
     var split = recipients.Split(';');
     foreach (var s in split)
         collection.Add(s);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// 发送HTML格式邮件(UTF8)
        /// </summary>
        public static SendStatus MailTo(SmtpConfig config, MailAddress AddrFrom, MailAddress AddrTo, MailAddressCollection cc, MailAddressCollection bCC,
            string Subject, string BodyContent, bool isHtml, List<Attachment> attC)
        {
            MailMessage msg = new MailMessage(AddrFrom == null ? new MailAddress(config.FromAddress) : AddrFrom, AddrTo);
            msg.Priority = MailPriority.High;

            #region 抄送
            if (cc != null && cc.Count > 0)
            {
                foreach (MailAddress cAddr in cc)
                {
                    msg.CC.Add(cAddr);
                }
            }
            #endregion

            #region 密送
            if (bCC != null && bCC.Count > 0)
            {
                foreach (MailAddress cAddr in bCC)
                {
                    msg.Bcc.Add(cAddr);
                }
            }
            #endregion

            #region 附件列表
            if (attC != null && attC.Count > 0)
            {
                foreach (Attachment item in attC)
                {
                    msg.Attachments.Add(item);
                }
            }
            #endregion

            msg.Subject = Subject;
            msg.SubjectEncoding = config.ContentEncoding;
            msg.BodyEncoding = config.ContentEncoding;
            msg.IsBodyHtml = isHtml;
            msg.Body = BodyContent;
            SmtpClient client = new SmtpClient(config.SmtpServer, config.Port);
            if (config.Credentials != null)
                client.Credentials = config.Credentials;
            client.EnableSsl = config.SSLConnect;

            SendStatus status = new SendStatus();
            try
            {
                client.Send(msg);
                status.Success = true;
            }
            catch (Exception exp)
            {
                status.Message = exp.Message;
            }
            return status;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Populates <paramref name="target"/> with properties copied from <paramref name="source"/>.
        /// </summary>
        /// <param name="source">The source object to copy.</param>
        /// <param name="target">The target object to populate.</param>
        private void Convert(MailAddressSerializableList source, MailAddressCollection target)
        {
            if (source == null)
            {
                return;
            }

            source.ForEach(s => target.Add(this.Convert(s)));
        }
Ejemplo n.º 20
0
        private void AddMailAddress(MailAddressCollection collection, IEnumerable<string> addressList)
        {
            if (collection == null || addressList == null)
                return;

            foreach (string add in addressList)
            {
                collection.Add(add);
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:EmailTraceListener"/> class.
 /// </summary>
 /// <param name="toAddress">The recipient e-mail address.</param>
 /// <param name="name">The name of the listener.</param>
 /// <exception cref="System.ArgumentNullException"><paramref name="toAddress"/> is a null reference.</exception>
 public EmailTraceListener(MailAddress toAddress, String name)
     : base(name)
 {
     if (toAddress == null) {
         throw new ArgumentNullException("toAddress");
     }
     this._toAddresses = new MailAddressCollection() {
         toAddress
     };
 }
Ejemplo n.º 22
0
        public static void Send(string from, string fromName, string replyTo, string replyToName, string[] to, string subject, string body)
        {
            MailAddressCollection toList = new MailAddressCollection();
            foreach (string item in to)
            {
                toList.Add(new MailAddress(item));
            }

            Send(new MailAddress(from, fromName), new MailAddress(replyTo, replyToName), toList, subject, body);
        }
        /// <summary>
        /// Initializes an instance of the System.Net.Mail.MailAddressCollection class with To as collection.
        /// </summary>
        /// <param name="addressCollection">
        /// </param>
        public MailAddressCollectionWrap(MailAddressCollection addressCollection)
        {
            var mailAddressCollection = addressCollection;

            this.mailAddresses = new List<IMailAddress>();
            foreach (var mailAddress in mailAddressCollection)
            {
                this.mailAddresses.Add(new MailAddressWrap(mailAddress));
            }
        }
Ejemplo n.º 24
0
        private static string GetAddress(ICollection<string> addresses)
        {
            var ColletionAddressess = new MailAddressCollection();
            foreach (var address in addresses)
            {
                ColletionAddressess.Add(new MailAddress(address));
            }

            return String.Join(",", ColletionAddressess.Select(address => address.Address).ToArray());
        }
        public void Add_WithAddressAndDisplayName_DoesAdd()
        {
            // Arrange
            var collection = new MailAddressCollection();

            // Act
            collection.Add(ObjectMother.To.Address, ObjectMother.To.DisplayName);

            // Assert
            Assert.That(collection, Has.Member(ObjectMother.To));
        }
Ejemplo n.º 26
0
    public static string sendmsg_toemail(string sender_name, string sender_email, string receiver_name, string receiver_email, string subject, string mymsg,string username,string password)
    {
        try

        {    // Create Mail Message Object with content that you want to send with mail.

           MailMessage MyMailMessage = new MailMessage();

           MailAddressCollection adcol = new MailAddressCollection();

                MyMailMessage.From = new MailAddress(sender_email, sender_name);
                //MyMailMessage.ReplyTo = new MailAddress(sender_email, sender_name);
                MyMailMessage.To.Add(new MailAddress(receiver_email, receiver_name));
                MyMailMessage.Subject =subject;
                MyMailMessage.Body = mymsg;
                MyMailMessage.IsBodyHtml = true;
            // Proper Authentication Details need to be passed when sending email from gmail
                System.Net.NetworkCredential mailAuthentication = new
                System.Net.NetworkCredential(username , password);

                // Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
                // For different server like yahoo this details changes and you can
                // Get it from respective server.
                System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

                // Enable SSL
                mailClient.EnableSsl = true;

                mailClient.UseDefaultCredentials = false;

                mailClient.Credentials = mailAuthentication;

                mailClient.Send(MyMailMessage);
                return "Done";

        }
        catch (System.Net.Mail.SmtpException ex)
        {
            string value=ex.Message.ToString();
            if (ex.InnerException.ToString().StartsWith("The remote name could not be resolved"))
            {
                return "<center><b style='color:red'>Please check your network connection.</b></center>";
            }
            else if (ex.Message.ToString().StartsWith("Failure sending mail"))
            {
                return "<center><b style='color:red'>Oops! some error occured. Please try later</b></center>";
            }
            else
            {
                return "<center><b style='color:red'>Oops! some error occured. Please try later</b></center>";
            }

        }
    }
Ejemplo n.º 27
0
        public MailMessage()
        {
            this.To = new MailAddressCollection();

            AlternateViews = new AlternateViewCollection();
            Attachments = new AttachmentCollection();
            Bcc = new MailAddressCollection();
            CC = new MailAddressCollection();
            ReplyToList = new MailAddressCollection();
            Headers = new Dictionary<string, string> {{"MIME-Version", "1.0"}};
        }
 public static void Run()
 {
     // ExStart:AddMembersToPrivateDistributionList
     IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
     ExchangeDistributionList[] distributionLists = client.ListDistributionLists();
     MailAddressCollection newMembers = new MailAddressCollection();
     newMembers.Add("*****@*****.**");
     newMembers.Add("*****@*****.**");
     client.AddToDistributionList(distributionLists[0], newMembers);
     // ExEnd:AddMembersToPrivateDistributionList
 }
Ejemplo n.º 29
0
        public void MailAddressCollection_Basic1()
        {
            MailAddressCollection mc = null;
            MailAddress m = null;

            mc = new MailAddressCollection("*****@*****.**");
            m = mc.MailAddresses[0];
            Assert.AreEqual("*****@*****.**", m.Value);
            Assert.AreEqual("bill", m.UserName);
            Assert.AreEqual("microsoft.com", m.DomainName);
        }
Ejemplo n.º 30
0
 bool RecipientsAccepted(MailAddressCollection tos)
 {
     if (tos!=null)
     {
         //bool allAccepted = true;
         foreach (MailAddress to in tos)
         {
            // if (RecipientAccepted(to)
         }
     }
     return false;
 }
        public MailMessage Build(MailAddress recipient)
        {
            var template              = GetTemplate();
            var messageBuilder        = new MailMessageBuilder();
            var mailMessageCollection = new MailAddressCollection()
            {
                recipient
            };

            return(messageBuilder
                   .From(new MailAddress(MailConfig.DefaultSender.From, MailConfig.DefaultSender.Name))
                   .WithSender(new MailAddress(MailConfig.DefaultSender.From, MailConfig.DefaultSender.Name))
                   .WithSubject("Password Reset Successful")
                   .WithHtmlBody(template)
                   .AddRecipients(mailMessageCollection)
                   .Build());
        }
Ejemplo n.º 32
0
 private static void FillMailAddressCollection(MailAddressCollection mailAddressCollection, List <string> addressList)
 {
     if (addressList == null || addressList.Count <= 0)
     {
         return;
     }
     addressList.ForEach(
         delegate(string address)
     {
         if (!string.IsNullOrEmpty(address))
         {
             MailAddress mailAddress = new MailAddress(address);
             mailAddressCollection.Add(mailAddress);
         }
     }
         );
 }
Ejemplo n.º 33
0
        /// <summary>
        /// 解析分解邮件地址
        /// </summary>
        /// <param name="mailAddress">邮件地址列表</param>
        /// <param name="mailAddressCollection">邮件地址对象</param>
        protected static void PaserMailAddress(List <string> mailAddress,
                                               MailAddressCollection mailAddressCollection)
        {
            if (mailAddress == null || mailAddress.Count == 0)
            {
                return;
            }

            foreach (var address in mailAddress)
            {
                if (address.Trim() == string.Empty)
                {
                    continue;
                }
                mailAddressCollection.Add(new MailAddress(address));
            }
        }
Ejemplo n.º 34
0
        public int Send(IEnumerable <string> recipients, string subject, string body, Action errorAction = null, Action successAction = null)
        {
            try
            {
                if (recipients != null && recipients.Any())
                {
                    using (SmtpClient client = new SmtpClient()
                    {
                        Host = email_Host,
                        Port = email_Port,
                        Credentials = new NetworkCredential(email_UserName, email_Password),
                        EnableSsl = false,//设置为true会出现"服务器不支持安全连接的错误"
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                    })
                    {
                        #region Send Message
                        var mail = new MailMessage
                        {
                            From       = new MailAddress(email_Address, email_DisplayName),
                            Subject    = subject,
                            Body       = body,
                            IsBodyHtml = true,
                        };
                        MailAddressCollection mailAddressCollection = new MailAddressCollection();
                        recipients.ToList().ForEach(i =>
                        {
                            //email有效性验证
                            if (new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$").IsMatch(i))
                            {
                                mail.To.Add(i);
                            }
                        });

                        client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                        client.SendAsync(mail, recipients);
                        #endregion
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Info(ex.Message);
                return(0);
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Send an e-mail with the specified properties. The e-mail will appear to come from the name and email specified in the
        /// <see cref="IAppSetting.EmailFromName" /> and <see cref="IAppSetting.EmailFromAddress" /> configuration settings.
        /// If <paramref name="sendOnBackgroundThread"/> is <c>true</c>, the e-mail is sent on a background thread and the function
        /// returns immediately. An exception is thrown if an error occurs while sending the e-mail, unless <paramref name="sendOnBackgroundThread"/>
        /// is true, in which case the error is logged but the exception does not propagate back to the calling thread.
        /// </summary>
        /// <param name="emailRecipients">The e-mail recipients.</param>
        /// <param name="subject">The text to appear in the subject of the email.</param>
        /// <param name="body">The body of the e-mail. If the body is HTML, specify true for <paramref name="isBodyHtml" />.</param>
        /// <param name="isBodyHtml">Indicates whether the body of the e-mail is in HTML format. When false, the body is
        ///   assumed to be plain text.</param>
        /// <param name="sendOnBackgroundThread">If set to <c>true</c>, send e-mail on a background thread. This causes any errors
        ///   to be silently handled by the error logging system, so if it is important for any errors to propogate to the caller,
        ///   such as when testing the e-mail function in the Site Administration area, set to <c>false</c>.</param>
        /// <exception cref="WebException">Thrown when a SMTP Server is not specified. (Not thrown when
        /// <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        /// <exception cref="SmtpException">Thrown when the connection to the SMTP server failed, authentication failed,
        /// or the operation timed out. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        /// <exception cref="SmtpFailedRecipientsException">The message could not be delivered to one or more of the
        /// <paramref name="emailRecipients"/>. (Not thrown when <paramref name="sendOnBackgroundThread"/> is true.)</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="emailRecipients" /> is null.</exception>
        public static void SendEmail(MailAddressCollection emailRecipients, string subject, string body, bool isBodyHtml, bool sendOnBackgroundThread)
        {
            if (emailRecipients == null)
            {
                throw new ArgumentNullException("emailRecipients");
            }

            var appSettings = AppSetting.Instance;

            MailAddress emailSender = new MailAddress(appSettings.EmailFromAddress, appSettings.EmailFromName);
            MailMessage mail        = null;

            try
            {
                mail = new MailMessage();
                foreach (MailAddress mailAddress in emailRecipients)
                {
                    mail.To.Add(mailAddress);
                }
                mail.From       = emailSender;
                mail.Subject    = subject;
                mail.Body       = body;
                mail.IsBodyHtml = isBodyHtml;

                // Because sending the e-mail takes a long time, spin off a thread to send it, unless caller specifically doesn't want to.
                if (sendOnBackgroundThread)
                {
                    Task.Factory.StartNew(() => SendEmail(mail, false));
                }
                else
                {
                    SendEmail(mail, false);
                    mail.Dispose();
                }
            }
            catch
            {
                if (mail != null)
                {
                    mail.Dispose();
                }

                throw;
            }
        }
        // ExStart:SendMeetingRequests
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Create an instance of SMTPClient
                SmtpClient client = new SmtpClient(txtMailServer.Text, txtUsername.Text, txtPassword.Text);
                // Get the attendees
                MailAddressCollection attendees = new MailAddressCollection();
                foreach (DataGridViewRow row in dgAttendees.Rows)
                {
                    if (row.Cells["EmailAddress"].Value != null)
                    {
                        // Get names and addresses from the grid and add to MailAddressCollection
                        attendees.Add(new MailAddress(row.Cells["EmailAddress"].Value.ToString(),
                                                      row.Cells["FirstName"].Value.ToString() + " " + row.Cells["LastName"].Value.ToString()));
                    }
                }

                // Create an instance of MailMessage for sending the invitation
                MailMessage msg = new MailMessage();

                // Set from address, attendees
                msg.From = txtFrom.Text;
                msg.To   = attendees;

                // Create am instance of Appointment
                Appointment app = new Appointment(txtLocation.Text, dtTimeFrom.Value, dtTimeTo.Value, txtFrom.Text, attendees);
                app.Summary     = "Monthly Meeting";
                app.Description = "Please confirm your availability.";
                msg.AddAlternateView(app.RequestApointment());

                // Save the info to the database
                if (SaveIntoDB(msg, app) == true)
                {
                    // Save the message and Send the message with the meeting request
                    msg.Save(msg.MessageId + ".eml", SaveOptions.DefaultEml);
                    client.Send(msg);
                    MessageBox.Show("message sent");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 37
0
        public ActionResult Contact(ContactViewModel contactViewModel)
        {
            if (!ModelState.IsValid)
            {
                foreach (var error in ViewData.ModelState["FullName"].Errors)
                {
                    ModelState.AddModelError(String.Empty, error.ErrorMessage);
                }
                foreach (var error in ViewData.ModelState["EmailAddress"].Errors)
                {
                    ModelState.AddModelError(String.Empty, error.ErrorMessage);
                }
                foreach (var error in ViewData.ModelState["Message"].Errors)
                {
                    ModelState.AddModelError(String.Empty, error.ErrorMessage);
                }


                return(View("Index", contactViewModel));
            }
            StringBuilder body = new StringBuilder();

            body.AppendLine("New Correspondence From perfectplacementservices.com:<br/>");
            body.AppendFormat("Name : {0}<br/>", contactViewModel.FullName).AppendLine();
            body.AppendFormat("Message: {0}", contactViewModel.Message.Replace("\r\n", "<br/>")).AppendLine();

            MailAddress           from         = new MailAddress(contactViewModel.EmailAddress, contactViewModel.FullName);
            MailAddressCollection toCollection = new MailAddressCollection();
            MailAddress           to           = new MailAddress("*****@*****.**");

            toCollection.Add(to);
            MailMessage message = new MailMessage();

            message.From = from;
            message.Body = body.ToString();
            message.To.Add(to);
            message.IsBodyHtml = true;
            message.Subject    = "New Correspondence From perfectplacementservices.com";



            EmailService.SendEmail(message);

            return(RedirectToAction("Success"));
        }
Ejemplo n.º 38
0
        public void ToMailMessageSimpleDoesNotThrowExceptionWhenABccRFCMailAddressDoesNotHaveValidMailAddress()
        {
            const string message =
                "CC: Test no email\r\n" +
                "\r\n" +                 // Headers end
                "Test";

            MailMessage mailMessage = new OPMessage(Encoding.ASCII.GetBytes(message)).ToMailMessage();

            Assert.NotNull(mailMessage);

            MailAddressCollection bcc = mailMessage.Bcc;

            Assert.NotNull(bcc);

            // The email address cannot be parsed to MailMessage - therefore it cannot be added to the MailMessage
            Assert.IsEmpty(bcc);
        }
Ejemplo n.º 39
0
        public void ToMailMessageSimpleHasCorrectBcc()
        {
            const string message =
                "BCC: Test <*****@*****.**>\r\n" +
                "\r\n" +                 // Headers end
                "Test";

            MailMessage mailMessage = new OPMessage(Encoding.ASCII.GetBytes(message)).ToMailMessage();

            Assert.NotNull(mailMessage);

            MailAddressCollection bcc = mailMessage.Bcc;

            Assert.NotNull(bcc);
            Assert.AreEqual(1, bcc.Count);
            Assert.AreEqual("Test", bcc[0].DisplayName);
            Assert.AreEqual("*****@*****.**", bcc[0].Address);
        }
Ejemplo n.º 40
0
        public void ToMailMessageSimpleHasCorrectTo()
        {
            const string message =
                "To: Test <*****@*****.**>\r\n" +
                "\r\n" +                 // Headers end
                "Test";

            MailMessage mailMessage = new OPMessage(Encoding.ASCII.GetBytes(message)).ToMailMessage();

            Assert.NotNull(mailMessage);

            MailAddressCollection to = mailMessage.To;

            Assert.NotNull(to);
            Assert.AreEqual(1, to.Count);
            Assert.AreEqual("Test", to[0].DisplayName);
            Assert.AreEqual("*****@*****.**", to[0].Address);
        }
Ejemplo n.º 41
0
        public static MailAddressCollection ParseRecipients(string address)
        {
            address = Nhea.Text.StringHelper.TrimText(address, true, Nhea.Text.TextCaseMode.lowercase).Trim(',').Trim(';');
            address = Nhea.Text.StringHelper.ReplaceNonInvariantCharacters(address);

            MailAddressCollection mailAddressCollection = new MailAddressCollection();

            char[] spliters = new char[] { ',', ';' };

            string[] mailArray = address.Split(spliters, StringSplitOptions.RemoveEmptyEntries);

            foreach (string str in mailArray)
            {
                mailAddressCollection.Add(str);
            }

            return(mailAddressCollection);
        }
Ejemplo n.º 42
0
 public static void Add(IQueryable <User> users, MailAddressCollection c)
 {
     if (users != null)
     {
         foreach (var s in users.Select(f => f.Email))
         {
             try
             {
                 var m = new MailAddress(s);
                 c.Add(m);
             }
             catch (Exception ex)
             {
                 log.Error(ex.Message, ex);
             }
         }
     }
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Depending on the mail address type, add each mail address from the collection to the mail message
 /// </summary>
 /// <param name="mail">This is the MailMessage object from the main form</param>
 /// <param name="mailAddrCol">This is the Collection of addresses that need to be added</param>
 /// <param name="mailAddressType">type of mail address to be added</param>
 public static void AddSmtpToMailAddressCollection(MailMessage mail, MailAddressCollection mailAddrCol, addressType mailAddressType)
 {
     foreach (MailAddress ma in mailAddrCol)
     {
         if (mailAddressType == addressType.To)
         {
             mail.To.Add(ma.Address);
         }
         else if (mailAddressType == addressType.Cc)
         {
             mail.CC.Add(ma.Address);
         }
         else
         {
             mail.Bcc.Add(ma.Address);
         }
     }
 }
Ejemplo n.º 44
0
        /// <summary>
        /// find individual addresses in the string and add it to address collection
        /// </summary>
        /// <param name="Addresses">string with possibly several email addresses</param>
        /// <param name="AddressCollection">parsed addresses</param>
        private void AddMailAddresses(string Addresses, MailAddressCollection AddressCollection)
        {
            MailAddress adr;

            try {
                string[] AddressSplit = Addresses.Split(',');
                foreach (string adrString in AddressSplit)
                {
                    adr = ConvertToMailAddress(adrString);
                    if (adr != null)
                    {
                        AddressCollection.Add(adr);
                    }
                }
            } catch {
                System.Diagnostics.Debugger.Break(); //didn't have a sample email to test this
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 邮件地址集合ToString()
        /// </summary>
        /// <param name="mailAddressCollection"></param>
        /// <returns></returns>
        private static string ToStringExt(this MailAddressCollection mailAddressCollection)
        {
            if (mailAddressCollection == null)
            {
                return(string.Empty);
            }
            StringBuilder sb = new StringBuilder();

            foreach (MailAddress item in mailAddressCollection)
            {
                if (sb.Length > 0)
                {
                    sb.Append(",");
                }
                sb.Append(item.ToStringExt());
            }
            return(sb.ToString());
        }
Ejemplo n.º 46
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="aMailAddressCollection"></param>
        /// <param name="Addreses"></param>
        private void AddAddress(MailAddressCollection aMailAddressCollection, string Addreses)
        {
            string[]    Temp = Addreses.Split(',');
            MailAddress itm;

            if (Temp == null)
            {
                return;
            }
            for (int i = 0; i < Temp.Length; i++)
            {
                if (Temp[i].Trim() != "")
                {
                    itm = new MailAddress(Temp[i]);
                    aMailAddressCollection.Add(itm);
                }
            }
        }
Ejemplo n.º 47
0
        //------------------------------------------
        //Get collection string from  mail address collection
        //------------------------------------------
        public static string GetCollectionStringFromMailAddressCollection(MailAddressCollection collection)
        {
            string adressesString = "";

            if (collection != null && collection.Count > 0)
            {
                foreach (MailAddress item in collection)
                {
                    if (adressesString.Length > 0)
                    {
                        adressesString += ",";
                    }

                    adressesString += (string)item.Address;
                }
            }
            return(adressesString);
        }
Ejemplo n.º 48
0
 private static void LoadMailAddresses(MailAddressCollection addresses, string addressHeaderValue)
 {
     try
     {
         if (!string.IsNullOrEmpty(addressHeaderValue))
         {
             addresses.Add(addressHeaderValue);
         }
     }
     catch (Exception ex)
     {
         //swallow exception thrown by bad data.
         if (!(ex is FormatException))
         {
             throw ex;
         }
     }
 }
Ejemplo n.º 49
0
        public MailMessage Build(string activationUrl, MailAddress recipient)
        {
            var template              = GetTemplate();
            var content               = template.Replace("{{PasswordResetUrl}}", activationUrl);
            var messageBuilder        = new MailMessageBuilder();
            var mailMessageCollection = new MailAddressCollection()
            {
                recipient
            };

            return(messageBuilder
                   .From(new MailAddress(MailConfig.DefaultSender.From, MailConfig.DefaultSender.Name))
                   .WithSender(new MailAddress(MailConfig.DefaultSender.From, MailConfig.DefaultSender.Name))
                   .WithSubject("Activate your Email")
                   .WithHtmlBody(content)
                   .AddRecipients(mailMessageCollection)
                   .Build());
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Send the email.
        /// </summary>
        /// <param name="EmailFrom"></param>
        /// <param name="EmailTo"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="Attachments"></param>
        /// <param name="CC"></param>
        /// <param name="BCC"></param>
        /// <param name="SMTPServer"></param>
        /// <param name="Mailformat"></param>
        /// <returns></returns>
        public bool SendMail(MailAddress EmailFrom, MailAddressCollection EmailTo, string Subject, string Body, AttachmentCollection AttachmentFiles, MailAddressCollection CC, MailAddressCollection BCC, SmtpClient SMTPServer, bool IsBodyHtml)
        {
            try
            {
                MailMessage Newmail = new MailMessage();
                Newmail.IsBodyHtml = IsBodyHtml;
                Newmail.Subject    = Subject;
                Newmail.Body       = Body;
                Newmail.From       = EmailFrom;
                Newmail.Sender     = EmailFrom;
                foreach (MailAddress recepient in EmailTo)
                {
                    Newmail.To.Add(recepient);
                }

                foreach (MailAddress ccrecepient in CC)
                {
                    Newmail.CC.Add(ccrecepient);
                }

                foreach (MailAddress bccrecepient in BCC)
                {
                    Newmail.CC.Add(bccrecepient);
                }

                foreach (Attachment attachment in AttachmentFiles)
                {
                    Newmail.Attachments.Add(attachment);
                }

                if (SMTPServer.Host != string.Empty)
                {
                    SMTPServer.Host = "localhost";
                }

                SMTPServer.Send(Newmail);

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 51
0
        public static bool SendEmail(string from, string commaSeperatedRecipients, string subject, string body, bool sendAsBcc)
        {
            try
            {
                MailMessage           msg = new MailMessage();
                MailAddressCollection recipientCollection = new MailAddressCollection();
                foreach (string mailaddress in commaSeperatedRecipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                {
                    MailAddress recipient = new MailAddress(mailaddress);
                    recipientCollection.Add(recipient);
                }
                MailAddress fromAddress = new MailAddress(from);
                msg.From       = fromAddress;
                msg.Subject    = subject;
                msg.Body       = body;
                msg.IsBodyHtml = true;
                if (sendAsBcc)
                {
                    msg.To.Add(fromAddress); // Set self as recipient
                    msg.Bcc.Add(recipientCollection.ToString());
                }
                else
                {
                    msg.To.Add(recipientCollection.ToString());
                }

                var        credential = new NetworkCredential(Globals.smtpUsername, Globals.smtpPassword);
                SmtpClient client     = new SmtpClient(Globals.smtpServer.Split(':')[0])
                {
                    Credentials = credential,
                    Port        = int.Parse(Globals.smtpServer.Split(':')[1])
                };
                client.Send(msg);
                return(true);
            }
            catch (Exception ex)
            {
                if (logLevel <= LogLevel.Warning)
                {
                    WriteLog("WRN: SendEmail() exception: " + ex.ToString());
                }
            }
            return(false);
        }
Ejemplo n.º 52
0
        private static void SendMail(string password, bool includeTimezone)
        {
            string fromEmail = "*****@*****.**";
            string toEmail   = "*****@*****.**";

            // client
            var client = new SmtpClient("smtp.gmail.com", 587, fromEmail, password);

            // message
            var message = new MailMessage(fromEmail, toEmail);

            message.Subject = "invite";
            message.Body    = "here's your invite";

            // appointment
            var currentDate = DateTime.Now;
            var attendees   = new MailAddressCollection();

            attendees.Add(toEmail);

            var startTime = new DateTime(2017, 9, 6, 9, 0, 0);
            var endTime   = startTime.AddHours(1);

            var appt = new Appointment("London", startTime, endTime, new MailAddress(fromEmail), attendees);

            //appt.Save(@"C:\scratch\Training Event Wizard1.ics", AppointmentSaveFormat.Ics);

            if (includeTimezone)
            {
                var tz = TimeZone.CurrentTimeZone;
                appt.SetTimeZone(tz.StandardName);
            }

            appt.Save(@"C:\scratch\Training Event Wizard3.ics", AppointmentSaveFormat.Ics);

            //message.Attachments.Add(new Attachment(@"C:\scratch\Training Event Wizard2.ics", string.Format("Calendar{0}.ics", 1)));
            message.Attachments.Add(new Attachment(@"C:\scratch\Training Event Wizard3.ics", "text/calendar"));

            client.Send(message);

            message.Dispose();

            Console.WriteLine("done");
        }
Ejemplo n.º 53
0
        private static void LogEmail(string body, string subject, MailAddressCollection mailTo, MailAddressCollection mailCc, MailAddressCollection mailBcc)
        {
            string timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd-HH-mm-ss-ffff");

            // create html file //

            try
            {
                string filePath = HttpContext.Current.Server.MapPath(Constants.ErrorLogPath + timeStamp + ".html");

                FileStream fs = File.Open(filePath, FileMode.CreateNew, FileAccess.Write);

                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);

                sw.WriteLine("<p><strong>Subject:</strong> " + subject + "</p>");
                sw.WriteLine("<p><strong>To:</strong> " + mailTo.ToString() + "</p>");
                sw.WriteLine("<p><strong>Cc:</strong> " + mailCc.ToString() + "</p>");
                sw.WriteLine("<p><strong>Bcc:</strong> " + mailBcc.ToString() + "</p>");
                sw.WriteLine("<p><strong>Timestamp:</strong> " + timeStamp + "</p>");

                sw.Write(body);

                sw.Close();
                fs.Close();

                // amend email log //

                string logFilePath = HttpContext.Current.Server.MapPath(Constants.EmailLogPath + "email-log.txt");

                fs = File.Open(logFilePath, FileMode.Append, FileAccess.Write);

                sw = new StreamWriter(fs, System.Text.Encoding.UTF8);

                sw.WriteLine(timeStamp + " - " + subject + " - " + mailTo.ToString());

                sw.Close();
                fs.Close();
            }
            catch (System.IO.IOException ex)
            {
                // throw away ex.
            }
        }
Ejemplo n.º 54
0
        private void GetAddressCollection(MailAddressCollection addressCollection, string delimitedAddresses)
        {
            string[] addressArray = null;
            int      inx          = 0;
            int      startInx     = 0;
            int      maxInx       = 0;

            if (delimitedAddresses.Length > 0)
            {
                //addressArray = delimitedAddresses.Split(',');
                addressArray = delimitedAddresses.Split(_addressDelimiters);
                startInx     = addressArray.GetLowerBound(0);
                maxInx       = addressArray.GetUpperBound(0);
                for (inx = startInx; inx <= maxInx; inx++)
                {
                    addressCollection.Add(new MailAddress(addressArray[inx]));
                }
            }
        }
        /// <summary>Add a list of e-mail addresses to the collection.</summary>
        /// <param name="addresses">
        ///     The e-mail addresses to add to the <see cref="T:Snork.SerializableMail.SerializableMailAddressCollection" />.
        ///     Multiple e-mail addresses must be separated with a comma character (",").
        /// </param>
        /// <exception cref="T:System.ArgumentNullException">The<paramref name=" addresses" /> parameter is null.</exception>
        /// <exception cref="T:System.ArgumentException">The<paramref name=" addresses" /> parameter is an empty string.</exception>
        /// <exception cref="T:System.FormatException">
        ///     The<paramref name="addresses" /> parameter contains an e-mail address that
        ///     is invalid or not supported.
        /// </exception>
        public void Add(string addresses)
        {
            if (addresses == null)
            {
                throw new ArgumentNullException();
            }
            if (addresses == string.Empty)
            {
                throw new ArgumentNullException();
            }
            var mailAddressCollection = new MailAddressCollection {
                addresses
            };

            foreach (var item in mailAddressCollection)
            {
                Add(item);
            }
        }
Ejemplo n.º 56
0
 public static bool ToEmail(string email)
 {
     try
     {
         var mailCollect = new MailAddressCollection();
         foreach (var item in email.Split(';'))
         {
             if (!string.IsNullOrEmpty(item))
             {
                 mailCollect.Add(item);
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Parses the address list in form of a string with individual addresses separated by the ';' character. The parsed
        /// addresses are then stored into the specified <see cref="MailAddressCollection"/>.
        /// </summary>
        /// <param name="collection">The mail address collection the parsed addresses should be stored into.</param>
        /// <param name="addresses">The addresses in form of a string.</param>
        public static void ParseAddresses(MailAddressCollection collection, string addresses)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            if (addresses == null)
            {
                throw new ArgumentNullException("addresses");
            }

            string[] addressesArray = addresses.Split(';');

            foreach (string address in addressesArray)
            {
                collection.Add(address);
            }
        }
Ejemplo n.º 58
0
        public async Task <MailMessage> Build(ActivationMailData mailData, MailAddress recipient)
        {
            var template = await GetHtmlTemplateAsync();

            var content = template.Replace("{{ActivationUrl}}", mailData.ActivationUrl)
                          .Replace("{{Name}}", mailData.Name);
            var messageBuilder        = new MailMessageBuilder();
            var mailMessageCollection = new MailAddressCollection {
                recipient
            };

            return(messageBuilder
                   .From(new MailAddress(MailConfig.From, MailConfig.Name))
                   .WithSender(new MailAddress(MailConfig.From, MailConfig.Name))
                   .WithSubject("Activate your Account")
                   .WithHtmlBody(content)
                   .AddRecipients(mailMessageCollection)
                   .Build());
        }
Ejemplo n.º 59
0
        public static bool Send(string TempateFile, Hashtable Replace, MailAddressCollection mailTo, string title, MailAddressCollection cc, MailAddressCollection bcc, string[] AttacheFile, bool SaveCannotSend, out string ErrorMessage, MailInfo MInfo)
        {
            string contents = "";

            try
            {
                contents = File.ReadAllText(TempateFile, System.Text.UTF8Encoding.UTF8);
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return(false);
            }
            foreach (DictionaryEntry Ent in Replace)
            {
                contents = contents.Replace(Ent.Key.ToString(), Ent.Value.ToString());
            }
            return(Send(mailTo, title, cc, bcc, contents, AttacheFile, SaveCannotSend, out ErrorMessage, MInfo));
        }
Ejemplo n.º 60
0
        public static string GetMailAddressesAsString(MailAddressCollection list)
        {
            string addresses = "";

            foreach (MailAddress item in list)
            {
                if (item.Address.Trim() != "")
                {
                    addresses += item.Address.Trim() + ";";
                }
            }

            if (addresses.EndsWith(";"))
            {
                addresses = addresses.Substring(0, addresses.Length - 1);
            }

            return(addresses);
        }