コード例 #1
0
ファイル: IdentityConfig.cs プロジェクト: FirasOmar/LeadMS
        public Task SendAsync(IdentityMessage message)
        {
            var smtp            = new System.Net.Mail.SmtpClient();
            var emailAddres     = SettingHelper.GetOrCreate(Core.Constants.SystemSettings.EmailsSourceEmail, "*****@*****.**").Value;
            var emailAddresName = SettingHelper.GetOrCreate(Core.Constants.SystemSettings.EmailsSourceName, "Crm Test").Value;
            var password        = SettingHelper.GetOrCreate(Core.Constants.SystemSettings.EmailsResetPassword, "Crm@123$").Value;
            var mail            = new System.Net.Mail.MailMessage
            {
                IsBodyHtml = true,
                From       = new System.Net.Mail.MailAddress(emailAddres, emailAddresName)
            };

            mail.To.Add(message.Destination);
            mail.Subject = message.Subject;
            mail.Body    = message.Body;

            smtp.Timeout     = 1000;
            smtp.Port        = int.Parse(SettingHelper.GetOrCreate(Core.Constants.SystemSettings.EmailsSmtpPort, "587").Value);
            smtp.Credentials = new NetworkCredential(emailAddres, password);
            smtp.Host        = SettingHelper.GetOrCreate(Core.Constants.SystemSettings.EmailsSmtpClient, "smtp-mail.outlook.com").Value;
            smtp.EnableSsl   = SettingHelper.GetOrCreate(Core.Constants.SystemSettings.EmailsEnableSsl, "true").Value.ToLower() == "true";

            var t = Task.Run(() => smtp.SendAsync(mail, null));

            return(t);
            // Plug in your email service here to send an email.
            //return Task.FromResult(0);
        }
コード例 #2
0
        private void SendMessage(System.Net.Mail.MailMessage mailMessage)
        {
            Object userState = mailMessage;

            try
            {
                smtpClient.SendAsync(mailMessage, userState);
            }
            catch (System.Net.Mail.SmtpFailedRecipientsException failedRec)
            {
                //Choose to resend?
                //Log failure of send here.
                failedRec.ToString();
            }
            catch (System.Net.Mail.SmtpException smtpExc)
            {
                //Log failure of SMTP client here.
                smtpExc.ToString();
            }
            catch (Exception ex)
            {
                //Log exception here.
                ex.ToString();
            }
        }
コード例 #3
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Name,EmailId,GuidId,SendDate")] SendInvitation sendInvitation)
        {
            if (ModelState.IsValid && User.Identity.IsAuthenticated)
            {
                var url = System.Configuration.ConfigurationManager.AppSettings.Get("RegisterUrl");

                var model = sendInvitation;

                // Create Guid
                model.GuidId = Guid.NewGuid().ToString();

                // Create Date time stamp
                model.SendDate = DateTime.Now;

                string html = RenderViewToString(ControllerContext,
                                                 "~/views/SendInvitations/NotificationEmail.cshtml",
                                                 model, true);

                ViewBag.RenderedHtml = html;

                // Send email invitation to Subscriber through SMTP
                try {
                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings.Get("SmtpServer"));

                    System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(User.Identity.Name,
                                                                                       User.Identity.Name,
                                                                                       System.Text.Encoding.UTF8);
                    // Set destinations for the e-mail message.
                    System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(sendInvitation.EmailId.ToString());
                    // Specify the message content.
                    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);

                    // Insert message Body here.

                    message.Body = html;
                    // Include some non-ASCII characters in body and subject.
                    string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
                    message.Body           += Environment.NewLine + someArrows;
                    message.BodyEncoding    = System.Text.Encoding.UTF8;
                    message.Subject         = "Invitation from ACME" + someArrows;
                    message.SubjectEncoding = System.Text.Encoding.UTF8;
                    // Set the method that is called back when the send operation ends.
                    // client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                    string userState = "Invitation";
                    client.SendAsync(message, userState);
                }
                catch (Exception Ex)
                {
                }


                db.SendInvitations.Add(sendInvitation);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(sendInvitation));
        }
コード例 #4
0
        public override string output(System.Collections.ArrayList columnHeaders,
            System.Collections.ArrayList rows,
            System.Collections.Hashtable rowLengthLookup)
        {
            //email://[email protected]/Trial Signup Report

            Regex regex = new Regex(
              "(?<Proto>[a-zA-Z]*)://(?<ToAddress>[a-zA-Z@._-]*)/(?<Subject"+
              ">[\\sa-zA-Z@._-]*)",
            RegexOptions.CultureInvariant
            | RegexOptions.Compiled
            );

            if (regex.IsMatch(PropertyBag.GetProperty("data.output")))
            {
                Match match = regex.Match(PropertyBag.GetProperty("data.output"));
                string emailAddress = match.Groups[2].Value;
                string subject = match.Groups[3].Value;

                Console.WriteLine("Sending email to: " + emailAddress);
                string bodySrc = "";

                if (PropertyBag.GetProperty("data.html", "false").ToLower() == "true")
                {
                    OutputMethod_HTML output = new OutputMethod_HTML();
                    bodySrc = output.output(columnHeaders, rows, rowLengthLookup);
                }
                else {
                    OutputMethod_TXTOnly output = new OutputMethod_TXTOnly();
                    bodySrc = output.output(columnHeaders, rows, rowLengthLookup);
                }

                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
                    PropertyBag.GetProperty("mail.fromaddress", "local@localhost"),
                    emailAddress,
                    subject,
                    bodySrc);

                if (PropertyBag.GetProperty("data.html", "false").ToLower() == "true")
                    message.IsBodyHtml = true;

                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(
                    PropertyBag.GetProperty("mail.smtpserver", "127.0.0.1"), 25);

                client.SendCompleted += (a, b) =>
                {
                    Console.WriteLine("[ERROR] Failed to send email.");
                };

                client.SendAsync(message, message);

            }

            return "";
        }
コード例 #5
0
ファイル: WinformTools.cs プロジェクト: weisimin/WeixinRobot
        public static void EMail_SendEmail(string Server, Int32 Port, bool EnableSSL, string UserName, string Password, System.Net.Mail.MailAddress FromAddress, List <System.Net.Mail.MailAddress> To, List <System.Net.Mail.MailAddress> CC, string Subject, string BodyHtml, List <System.Net.Mail.Attachment> attachlist)
        {
            //简单邮件传输协议类
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host      = Server; //邮件服务器
            client.Port      = Port;   //smtp主机上的端口号,默认是25.
            client.EnableSsl = EnableSSL;

            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;//邮件发送方式:通过网络发送到SMTP服务器

            client.UseDefaultCredentials = true;
            client.Credentials           = new NetworkCredential(UserName, Password);;//凭证,发件人登录邮箱的用户名和密码



            //电子邮件信息类
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();//创建一个电子邮件类
            //似乎部分邮件不允许显示人改名
            mailMessage.From = FromAddress;

            foreach (System.Net.Mail.MailAddress item in To)
            {
                mailMessage.To.Add(item);
            }
            foreach (System.Net.Mail.MailAddress item in CC)
            {
                mailMessage.CC.Add(item);
            }


            mailMessage.Subject         = Subject;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;              //邮件主题编码

            mailMessage.Body         = BodyHtml;                                  //可为html格式文本
            mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //邮件内容编码
            mailMessage.IsBodyHtml   = true;                                      //邮件内容是否为html格式

            mailMessage.Priority = System.Net.Mail.MailPriority.High;             //邮件的优先级,有三个值:高(在邮件主题前有一个红色感叹号,表示紧急),低(在邮件主题前有一个蓝色向下箭头,表示缓慢),正常(无显示).
            //附件
            foreach (System.Net.Mail.Attachment att in attachlist)
            {
                mailMessage.Attachments.Add(att);
            }
            //异步传输事件
            client.Timeout        = 60000;
            client.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(client_SendCompleted);
            try
            {
                client.SendAsync(mailMessage, mailMessage);//发送邮件
            }
            catch (Exception AnyError)
            {
                MessageBox.Show(AnyError.Message);
            }
        }
コード例 #6
0
 public void logMessage(MessageTO request)
 {
     //LOG.Error("An extraction job uploaded the following error: " + request.Error);
     try
     {
         System.Net.Mail.SmtpClient mail = new System.Net.Mail.SmtpClient("smtp.va.gov", 25);
         mail.SendAsync("*****@*****.**", "*****@*****.**", "Log Error Request From Client", request.Error, new object());
     }
     catch (Exception exc)
     {
         //LOG.Error("Unable to send email about error log request!", exc);
     }
 }
コード例 #7
0
    private static async Task SendMailExImplAsync(
        System.Net.Mail.SmtpClient client,
        System.Net.Mail.MailMessage message,
        CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        var tcs = new TaskCompletionSource <bool>();

        System.Net.Mail.SendCompletedEventHandler handler = null;
        Action unsubscribe = () => client.SendCompleted -= handler;

        handler = async(s, e) =>
        {
            unsubscribe();
            // a hack to complete the handler asynchronously
            await Task.Yield();

            if (e.UserState != tcs)
            {
                tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
            }
            else if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else
            {
                tcs.TrySetResult(true);
            }
        };
        client.SendCompleted += handler;
        try
        {
            client.SendAsync(message, tcs);
            using (token.Register(() => client.SendAsyncCancel(), useSynchronizationContext: false))
            {
                await tcs.Task;
            }
        }
        finally
        {
            unsubscribe();
        }
    }
コード例 #8
0
        public Task SendAsync(IdentityMessage message)
        {
            // 在此处插入电子邮件服务可发送电子邮件。
            //配置
            var mailMessage = new System.Net.Mail.MailMessage(
                "@.",//email
                message.Destination,
                message.Subject,
                message.Body);
            //发送
            var client = new System.Net.Mail.SmtpClient();

            client.SendAsync(mailMessage, null);

            return(Task.FromResult(0));
        }
コード例 #9
0
        public Task SendAsync(IdentityMessage message)
        {
            var smtp = new System.Net.Mail.SmtpClient();
            var mail = new System.Net.Mail.MailMessage();

            mail.IsBodyHtml = true;
            mail.From       = new System.Net.Mail.MailAddress("*****@*****.**", "System Admin");
            mail.To.Add(message.Destination);
            mail.Subject = message.Subject;
            mail.Body    = message.Body;

            smtp.Timeout = 1000;

            var t = Task.Run(() => smtp.SendAsync(mail, null));

            return(t);

            // Plug in your email service here to send an email.
            //return Task.FromResult(0);
        }
コード例 #10
0
        /// <summary>
        /// Send Email
        /// </summary>
        /// <param name="emailFrom">from who</param>
        /// <param name="emailTo">to </param>
        /// <param name="body">Body Message</param>
        public static void SendEmail(string emailFrom, string emailTo, string body)
        {
            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(emailFrom, emailTo);
                message.CC.Add(emailFrom);
                message.Subject         = "TFS : Code Review demandé";
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                message.Body            = body;
                message.BodyEncoding    = System.Text.Encoding.UTF8;
                message.IsBodyHtml      = true;

                System.Net.Mail.SmtpClient mail = new System.Net.Mail.SmtpClient(settings.SmtpHost);
                mail.Credentials = tfsColl.Credentials.GetCredential(new Uri(settings.SmtpURI), AuthenticationSchemes.Digest.ToString());
                mail.SendAsync(message, emailTo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Impossible d'envoyer l'email \n\r" + ex.Message);
            }
        }
コード例 #11
0
ファイル: Email.cs プロジェクト: nwelsheimer/aerialdb
        public static void SendEmail(string MessageText, string Version)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.From = new System.Net.Mail.MailAddress("*****@*****.**");
            message.To.Add("*****@*****.**");
            message.Subject = string.Format("Error message from Aerial.db - WOP");
            message.Body    = string.Format("Version: {0}\r\nMachine: {1}\r\nUser: {2}\r\nMessage: {3}",
                                            Version,
                                            System.Environment.MachineName,
                                            System.Environment.UserName,
                                            MessageText);

            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com");
            client.Port = 587;
            client.UseDefaultCredentials = false;
            client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "MjkDUBmouxNztGmm8aH-");
            client.EnableSsl             = true;

            try {
                client.SendAsync(message, null);
            }
            catch { }
        }
コード例 #12
0
        public static bool Send(MailDto dto)
        {
            //简单邮件传输协议类
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host           = "smtp.163.com";                                              //邮件服务器
            client.Port           = 25;                                                          //smtp主机上的端口号,默认是25.
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;                  //邮件发送方式:通过网络发送到SMTP服务器
            client.Credentials    = new System.Net.NetworkCredential("xshuai1992", "xiaoshuai"); //凭证,发件人登录邮箱的用户名和密码

            //电子邮件信息类
            System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("*****@*****.**");     //发件人Email,在邮箱是这样显示的,[发件人:小明<*****@*****.**>;]
            System.Net.Mail.MailAddress toAddress   = new System.Net.Mail.MailAddress("*****@*****.**", "小红"); //收件人Email,在邮箱是这样显示的, [收件人:小红<*****@*****.**>;]
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(fromAddress, toAddress);   //创建一个电子邮件类
            mailMessage.Subject = "【xiaoshuai】" + dto.Subject;
            string mailBody = dto.Body;

            mailMessage.Body            = mailBody;                                   //可为html格式文本
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;                  //邮件主题编码
            mailMessage.BodyEncoding    = System.Text.Encoding.GetEncoding("GB2312"); //邮件内容编码
            mailMessage.IsBodyHtml      = true;                                       //邮件内容是否为html格式
            mailMessage.Priority        = System.Net.Mail.MailPriority.High;          //邮件的优先级,有三个值:高(在邮件主题前有一个红色感叹号,表示紧急),低(在邮件主题前有一个蓝色向下箭头,表示缓慢),正常(无显示).

            bool result = false;

            try
            {
                // client.Send(mailMessage);//发送邮件
                client.SendAsync(mailMessage, "ojb");//异步方法发送邮件,不会阻塞线程.
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
コード例 #13
0
        private void CommitReport()
        {
            if (isSending)
            {
                return;
            }

            if (descriptionText.Length <= 0)
            {
                //error message.
                SysPopup signPrompt = new SysPopup(Owner, Resource.MenuBugReportEmptyDescription);
                signPrompt.transitionOnTime  = 200;
                signPrompt.transitionOffTime = 200;
                signPrompt.darkenScreen      = true;
                signPrompt.hideChildren      = false;
                signPrompt.canBeExited       = false;
                signPrompt.sideIconRect      = sprite.windowIcon.error;

                MenuItem item = new MenuItem(Resource.MenuOK);
                item.Selected += ClosePopup;
                signPrompt.AddItem(item);

                Owner.AddMenu(signPrompt);
                return;
            }

            FrameworkCore.PlayCue(sounds.click.activate);

            isSending = true;

            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

                message.From = new System.Net.Mail.MailAddress("*****@*****.**");
                message.To.Add(new System.Net.Mail.MailAddress("*****@*****.**"));

                message.Subject = "[FLOTILLA] " + subjectText;



                string registered = string.Empty;
                if (FrameworkCore.isTrialMode())
                {
                    registered = "Demo";
                }
                else
                {
                    registered = "Registered";
                }

                string finalString = registered + " version " + FrameworkCore.VERSION + "\n\n" + descriptionText;

                message.Body = finalString;


                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                client.Host        = "smtp.gmail.com"; //smtp server
                client.Port        = 587;              //Port for TLS/STARTTLS
                client.EnableSsl   = true;
                client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "");


                client.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(client_SendCompleted);
                client.SendAsync(message, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #14
0
        /// <summary>
        /// Attempt to directly send an email messages via SMTP with given recipient, CC, subject, and attachments.
        /// </summary>
        /// <param name="sender">Email address of the sender.</param>
        /// <param name="recipient">Email address of the recipient.</param>
        /// <param name="ccList">Additional email addresses.</param>
        /// <param name="subject">The subject of the email.</param>
        /// <param name="message">The body of the email.</param>
        /// <param name="fileAttachments">An enumerable containing absolute paths of files to attach to the email.</param>
        /// <param name="token">Caller-specific data to be passed to the <paramref name="sendComplete"/> callback.</param>
        /// <param name="sendComplete">A function to call when the attempt to send the email message completes. May be <c>null</c>.</param>
        /// <remarks>NOTE: This code is experimental, and incomplete. To fully implement in general requires a proper SMTP configuration UI and
        /// data retention, which should properly encrypt the necessary information.</remarks>
        public static void SendEmailUsingSMTP(string sender, string recipient, IEnumerable <string> ccList, string subject, string message, IEnumerable <string> fileAttachments, object token, Action <Exception, bool, object> sendComplete)
        {
            // If the address isn't valid, just use a fake INTV Funhouse address.
            try
            {
                if (!string.IsNullOrWhiteSpace(sender))
                {
                    var address = new System.Net.Mail.MailAddress(sender);
                    sender = address.Address;
                }
                else
                {
                    sender = null;
                }
            }
            catch (FormatException)
            {
                sender = null;
            }
            sender = sender ?? "*****@*****.**";
            var smtpMessage = new System.Net.Mail.MailMessage(sender, recipient);

            smtpMessage.Subject = subject;
            smtpMessage.Body    = message;
            if ((ccList != null) && ccList.Any())
            {
                foreach (var address in ccList)
                {
                    try
                    {
                        var cc = new System.Net.Mail.MailAddress(address);
                        smtpMessage.CC.Add(cc);
                    }
                    catch (FormatException)
                    {
                    }
                }
            }

            if (fileAttachments != null)
            {
                foreach (var attachmentPath in fileAttachments)
                {
                    if (System.IO.File.Exists(attachmentPath))
                    {
                        var attachment = new System.Net.Mail.Attachment(attachmentPath);
                        attachment.ContentDisposition.CreationDate     = System.IO.File.GetCreationTime(attachmentPath);
                        attachment.ContentDisposition.ModificationDate = System.IO.File.GetLastWriteTime(attachmentPath);
                        attachment.ContentDisposition.ReadDate         = System.IO.File.GetLastAccessTime(attachmentPath);
                        attachment.ContentDisposition.FileName         = System.IO.Path.GetFileName(attachmentPath);
                        attachment.ContentDisposition.Size             = new System.IO.FileInfo(attachmentPath).Length;
                        attachment.ContentDisposition.DispositionType  = System.Net.Mime.DispositionTypeNames.Attachment;
                        smtpMessage.Attachments.Add(attachment);
                    }
                }
            }

            // HERE IS WHERE IT GETS ICKY. Don't feel like writing all the UI and safe data
            // management for the SMTP setup. Plus, some users may not what to set up all that
            // stuff again -- LUI is not an email client! And... who wants to write the code
            // that goes poking around the OS to see if this can be dug out some other way?
#if SMTP_SUPPORT
            var smtp = new System.Net.Mail.SmtpClient("some smtp host");
            smtp.EnableSsl = true;

            // TODO: Safely encrypt credentials to a store so they can be decrypted here and used.
            //       Need to store the SMTP client, port, user name, and password.
            // TODO: Write a config UI to determine whether the certificate checker is needed.
            // TODO: Who am I kidding, this is NOT a topic I'm familiar with.
            smtp.Credentials = new System.Net.NetworkCredential("user name", "password");
            smtp.Port        = 25; // have to get a proper port number here
            var completionToken = new Tuple <object, Action <Exception, bool, object> >(token, sendComplete);
            try
            {
                // Use custom certificate validation.
                System.Net.ServicePointManager.ServerCertificateValidationCallback += SendEmailCertificateChecker;
#if SMTP_SEND_SYNCHRONOUSLY
                smtp.Send(smtpMessage);
                SendEmailComplete(smtp, new System.ComponentModel.AsyncCompletedEventArgs(null, false, completionToken));
#else
                smtp.SendCompleted += SendEmailComplete;
                smtp.SendAsync(smtpMessage, completionToken);
#endif // SMTP_SEND_SYNCHRONOUSLY
            }
            catch (Exception e)
            {
                if (sendComplete != null)
                {
                    SendEmailComplete(smtp, new System.ComponentModel.AsyncCompletedEventArgs(e, false, completionToken));
                }
                else
                {
                    throw;
                }
            }
            finally
            {
#if SMTP_SEND_SYNCHRONOUSLY
                // Only do this if we use the synchronous send. If we do this when doing an async send,
                // we remove the checker before it actually gets a chance to run.
                System.Net.ServicePointManager.ServerCertificateValidationCallback -= SendEmailCertificateChecker;
#endif // SMTP_SEND_SYNCHRONOUSLY
            }
#else
            throw new NotImplementedException(Resources.Strings.SmtpSendNotImplemented);
#endif // SMTP_SUPPORT
        }
コード例 #15
0
 public override void SendAsync(System.Net.Mail.MailMessage message, object token)
 {
     client.SendAsync(message, token);
 }
コード例 #16
0
 public virtual void SendAsync(MailMessage message, object userToken)
 {
     _smtpClient.SendAsync(message, userToken);
 }
コード例 #17
0
        private static string SendMail(bool SendAsync, string DefaultConnection, string MailFrom, string MailTo, string MailToDisplayName, string Cc, string Bcc, string ReplyTo, string Header, System.Net.Mail.MailPriority Priority,
                                       string Subject, Encoding BodyEncoding, string Body, string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL)
        {
            string          strSendMail     = "";
            GeneralSettings GeneralSettings = new GeneralSettings(DefaultConnection);

            // SMTP server configuration
            if (SMTPServer == "")
            {
                SMTPServer = GeneralSettings.SMTPServer;

                if (SMTPServer.Trim().Length == 0)
                {
                    return("Error: Cannot send email - SMTPServer not set");
                }
            }

            if (SMTPAuthentication == "")
            {
                SMTPAuthentication = GeneralSettings.SMTPAuthendication;
            }

            if (SMTPUsername == "")
            {
                SMTPUsername = GeneralSettings.SMTPUserName;
            }

            if (SMTPPassword == "")
            {
                SMTPPassword = GeneralSettings.SMTPPassword;
            }

            MailTo = MailTo.Replace(";", ",");
            Cc     = Cc.Replace(";", ",");
            Bcc    = Bcc.Replace(";", ",");

            System.Net.Mail.MailMessage objMail = null;
            try
            {
                System.Net.Mail.MailAddress SenderMailAddress    = new System.Net.Mail.MailAddress(MailFrom, MailFrom);
                System.Net.Mail.MailAddress RecipientMailAddress = new System.Net.Mail.MailAddress(MailTo, MailToDisplayName);

                objMail = new System.Net.Mail.MailMessage(SenderMailAddress, RecipientMailAddress);

                if (Cc != "")
                {
                    objMail.CC.Add(Cc);
                }
                if (Bcc != "")
                {
                    objMail.Bcc.Add(Bcc);
                }

                if (ReplyTo != string.Empty)
                {
                    objMail.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo));
                }

                objMail.Priority   = (System.Net.Mail.MailPriority)Priority;
                objMail.IsBodyHtml = IsHTMLMail(Body);
                objMail.Headers.Add("In-Reply-To", $"ADefHelpDesk-{Header}");

                foreach (string myAtt in Attachment)
                {
                    if (myAtt != "")
                    {
                        objMail.Attachments.Add(new System.Net.Mail.Attachment(myAtt));
                    }
                }

                // message
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject         = Subject.Trim();
                objMail.BodyEncoding    = BodyEncoding;

                System.Net.Mail.AlternateView PlainView =
                    System.Net.Mail.AlternateView.CreateAlternateViewFromString(Utility.ConvertToText(Body),
                                                                                null, "text/plain");

                objMail.AlternateViews.Add(PlainView);

                //if body contains html, add html part
                if (IsHTMLMail(Body))
                {
                    System.Net.Mail.AlternateView HTMLView =
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

                    objMail.AlternateViews.Add(HTMLView);
                }
            }

            catch (Exception objException)
            {
                // Problem creating Mail Object
                strSendMail = MailTo + ": " + objException.Message;

                // Log Error to the System Log
                Log.InsertSystemLog(DefaultConnection, Constants.EmailError, "", strSendMail);
            }

            if (objMail != null)
            {
                // external SMTP server alternate port
                int?SmtpPort = null;
                int portPos  = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort   = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                if (SMTPServer != "")
                {
                    smtpClient.Host = SMTPServer;
                    smtpClient.Port = (SmtpPort == null) ? (int)25 : (Convert.ToInt32(SmtpPort));

                    switch (SMTPAuthentication)
                    {
                    case "":
                    case "0":
                        // anonymous
                        break;

                    case "1":
                        // basic
                        if (SMTPUsername != "" & SMTPPassword != "")
                        {
                            smtpClient.UseDefaultCredentials = false;
                            smtpClient.Credentials           = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
                        }

                        break;

                    case "2":
                        // NTLM
                        smtpClient.UseDefaultCredentials = true;
                        break;
                    }
                }
                smtpClient.EnableSsl = SMTPEnableSSL;

                try
                {
                    if (SendAsync) // Send Email using SendAsync
                    {
                        // Set the method that is called back when the send operation ends.
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;

                        // Send the email
                        DTOMailMessage objDTOMailMessage = new DTOMailMessage();
                        objDTOMailMessage.DefaultConnection = DefaultConnection;
                        objDTOMailMessage.MailMessage       = objMail;

                        smtpClient.SendAsync(objMail, objDTOMailMessage);
                        strSendMail = "";
                    }
                    else // Send email and wait for response
                    {
                        smtpClient.Send(objMail);
                        strSendMail = "";

                        // Log the Email
                        LogEmail(DefaultConnection, objMail);

                        objMail.Dispose();
                        smtpClient.Dispose();
                    }
                }
                catch (Exception objException)
                {
                    // mail configuration problem
                    if (!(objException.InnerException == null))
                    {
                        strSendMail = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message);
                    }
                    else
                    {
                        strSendMail = objException.Message;
                    }

                    // Log Error to the System Log
                    Log.InsertSystemLog(DefaultConnection, Constants.EmailError, "", strSendMail);
                }
            }

            return(strSendMail);
        }
コード例 #18
0
        public bool EnviarEmail()
        {
            if (CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVl_BoolTerminal("ST_ENVIAR_EMAIL_OUTLOOK", Utils.Parametros.pubTerminal, null))
            {
                if (Destinatario.Count > 0)
                {
                    try
                    {
                        if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count().Equals(0))
                        {
                            System.Diagnostics.ProcessStartInfo inf = new System.Diagnostics.ProcessStartInfo("OUTLOOK");
                            inf.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
                            System.Diagnostics.Process.Start(inf);
                        }
                        OutLook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
                        OutLook.MailItem    oMsg = oApp.CreateItem(OlItemType.olMailItem) as OutLook.MailItem;
                        //Titulo do email
                        oMsg.Subject = Titulo.Trim();
                        //Assinatura do usuário
                        object usu = new CamadaDados.Diversos.TCD_CadUsuario().BuscarEscalar(
                            new Utils.TpBusca[]
                        {
                            new Utils.TpBusca()
                            {
                                vNM_Campo = "a.login",
                                vOperador = "=",
                                vVL_Busca = "'" + Utils.Parametros.pubLogin.Trim() + "'"
                            }
                        }, "a.nome_usuario");
                        if (usu != null && !string.IsNullOrEmpty(usu.ToString()))
                        {
                            Mensagem = Mensagem.Trim() + "\n\n\n Ass.: " + usu;
                        }

                        //Mensagem do email
                        oMsg.HTMLBody = Mensagem.Trim();
                        if (Anexo.Count > 0)
                        {
                            int posicao = oMsg.Body.Length + 1;
                            int iAnexo  = Convert.ToInt32(OutLook.OlAttachmentType.olByValue);
                            int cont    = 1;
                            foreach (string a in Anexo)
                            {
                                oMsg.Attachments.Add(a, iAnexo, posicao, "Anexo" + (cont++).ToString());
                            }
                        }

                        //Destinatario
                        OutLook.Recipients r = oMsg.Recipients;
                        foreach (string d in Destinatario)
                        {
                            OutLook.Recipient oR = r.Add(d);
                            oR.Resolve();
                        }
                        //Enviar email
                        oMsg.Send();
                        return(true);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Erro enviar email: " + ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                //Objeto Email
                System.Net.Mail.MailMessage objemail = new System.Net.Mail.MailMessage();
                //Remetente do Email
                Remetente = CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("EMAIL_PADRAO", null).Trim().ToLower();
                if (string.IsNullOrEmpty(Remetente))
                {
                    MessageBox.Show("Não existe email padrão configurado.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }
                if (CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVL_Bool("ST_COPIA_EMAIL", string.Empty, null).Trim().ToUpper().Equals("S"))
                {
                    object obj = new CamadaDados.Diversos.TCD_CadUsuario().BuscarEscalar(
                        new Utils.TpBusca[]
                    {
                        new Utils.TpBusca()
                        {
                            vNM_Campo = "a.login",
                            vOperador = "=",
                            vVL_Busca = "'" + Utils.Parametros.pubLogin.Trim() + "'"
                        }
                    }, "a.email_padrao");
                    if (obj != null)
                    {
                        objemail.Bcc.Add(obj.ToString());
                    }
                }
                objemail.From = new System.Net.Mail.MailAddress(Remetente.Trim().ToLower());
                //Destinatario do Email
                if (Destinatario.Count < 1)
                {
                    MessageBox.Show("Obrigatorio informar destinatario para enviar email.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }
                foreach (string d in Destinatario)
                {
                    objemail.To.Add(new System.Net.Mail.MailAddress(d.Trim().ToLower()));
                }
                //Titulo do Email
                if (Titulo.Trim().Equals(string.Empty))
                {
                    MessageBox.Show("Obrigatorio informar titulo para enviar email.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }
                objemail.Subject = Titulo.Trim();
                //Assinatura do usuário
                object usu = new CamadaDados.Diversos.TCD_CadUsuario().BuscarEscalar(
                    new Utils.TpBusca[]
                {
                    new Utils.TpBusca()
                    {
                        vNM_Campo = "a.login",
                        vOperador = "=",
                        vVL_Busca = "'" + Utils.Parametros.pubLogin.Trim() + "'"
                    }
                }, "a.nome_usuario");
                if (usu != null && !string.IsNullOrEmpty(usu.ToString()))
                {
                    Mensagem = Mensagem.Trim() + "\n\n\n Ass.: " + usu;
                }
                //Mensagem do Email
                objemail.Body = Mensagem.Trim();
                //Html
                objemail.IsBodyHtml = St_html;
                //Anexos do email
                foreach (string str in Anexo)
                {
                    objemail.Attachments.Add(new System.Net.Mail.Attachment(str.Trim()));
                }
                //Configurar objeto SMTP
                Smtp = CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("SERVIDOR_SMTP", Utils.Parametros.pubTerminal, null);
                if (Smtp.Trim().Equals(string.Empty))
                {
                    MessageBox.Show("Não existe configuração de servidor smtp para o terminal " + Utils.Parametros.pubTerminal.Trim(), "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }
                System.Net.Mail.SmtpClient objsmtp = new System.Net.Mail.SmtpClient();
                if (CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlBool("CONEXAO_SSL_SMTP", null))
                {
                    objsmtp.EnableSsl = true;
                }
                objsmtp.Credentials = new System.Net.NetworkCredential(CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("EMAIL_PADRAO", null).Trim().ToLower(),
                                                                       CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("SENHA_EMAIL", null).Trim().ToLower());
                objsmtp.Host = Smtp.Trim().ToLower();
                //Configurar porta smtp
                Porta_smtp = Convert.ToInt32(CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlNumerico("PORTA_SMTP", Utils.Parametros.pubTerminal, null));
                if (Porta_smtp < 1)
                {
                    MessageBox.Show("Não existe configuração de porta smtp para o terminal " + Utils.Parametros.pubTerminal.Trim(), "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }
                objsmtp.Port = Porta_smtp;
                //Criar metodo email enviado
                objsmtp.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(objsmtp_SendCompleted);
                //Enviar Email
                try
                {
                    objsmtp.SendAsync(objemail, "Email enviado com sucesso");
                    return(true);
                }
                catch (System.Exception ex)
                {
                    throw new System.Exception("Erro enviar email: " + ex.Message.Trim());
                }
                finally
                {
                    objsmtp = null;
                }
            }
        }
コード例 #19
0
ファイル: WYEmail.cs プロジェクト: AlanWyu/WYTools
 public string SendEmail()
 {
     string result = "";
     try
     {
         System.Net.Mail.MailMessage mail = CreateMail();
         System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(host);
         smtp.Port = port;
         smtp.Timeout = 9999;
         smtp.Credentials = new System.Net.NetworkCredential(from, password);
         smtp.SendAsync(mail, null);
         smtp.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(smtp_SendCompleted);
         result = "ok";
     }
     catch (Exception ex)
     {
         result = ex.Message.ToString();
     }
     return result;
 }