Beispiel #1
0
        private async Task SendMail(User user, string callbackUrl)
        {
            Email email = new Email();

            email.ToEmailAddress = new EmailAddress()
            {
                Name = user.Name, Email = user.Email
            };
            email.FromEmailAddress = new EmailAddress()
            {
                Name = _emailServer.Name, Email = _emailServer.Username
            };

            var builder = new MimeKit.BodyBuilder();

            builder.HtmlBody = $"Please confirm your email by clicking <b><a href='{callbackUrl}'>here</a></b>";

            email.Message = builder.HtmlBody;
            email.Subject = "Activate Your Account";

            try
            {
                await _emailService.SendEmailAsync(email);
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #2
0
        public static void Mail(string id, string pass, string from, string to, string subject, string body, string path)
        {
            //Console.WriteLine("Hello SMTP World!");

            /*
             * string id = "<gmailのログインID>";
             * string pass = "******";
             * string from = "<宛先>";
             * string to = "<自分のメール>";
             * string subject = "送信テスト : " + DateTime.Now.ToString();
             * string body = "from t.masuda";
             */
#if false
            var smtp = new System.Net.Mail.SmtpClient();
            smtp.Host        = "smtp.gmail.com";                           //SMTPサーバ
            smtp.Port        = 587;                                        //SMTPポート
            smtp.EnableSsl   = true;
            smtp.Credentials = new System.Net.NetworkCredential(id, pass); //認証
            var msg = new System.Net.Mail.MailMessage(from, to, subject, body);
            smtp.Send(msg);                                                //メール送信
#else
            var smtp = new MailKit.Net.Smtp.SmtpClient();
            smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
            smtp.Authenticate(id, pass);

            var mail    = new MimeKit.MimeMessage();
            var builder = new MimeKit.BodyBuilder();

            mail.From.Add(new MimeKit.MailboxAddress("", from));
            mail.To.Add(new MimeKit.MailboxAddress("", to));
            mail.Subject     = subject;
            builder.TextBody = body;
            //mail.Body = builder.ToMessageBody();

            //var path = @"C:\Windows\Web\Wallpaper\Theme2\img10.jpg"; // 添付したいファイル
            var attachment = new MimeKit.MimePart("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                Content                 = new MimeKit.MimeContent(File.OpenRead(path)),
                ContentDisposition      = new MimeKit.ContentDisposition(),
                ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
                FileName                = System.IO.Path.GetFileName(path)
            };

            var multipart = new MimeKit.Multipart("mixed");
            multipart.Add(builder.ToMessageBody());
            multipart.Add(attachment);

            mail.Body = multipart;

            smtp.Send(mail);
            smtp.Disconnect(true);
#endif

            Console.WriteLine("メールを送信しました");
        }
Beispiel #3
0
        /// <summary>
        /// 使用MailKit发送邮件
        /// </summary>
        /// <param name="body">邮件内容</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="to">收件人集合</param>
        /// <param name="cc">抄送人集合</param>
        public void SendEmailByMailKit(string body, string subject, string[] to, string[] cc = null)
        {
            var message = new MimeKit.MimeMessage();

            //发件人
            message.From.Add(new MimeKit.MailboxAddress(_config.From, _config.From));
            //邮件主题
            message.Subject = (subject);
            //设置邮件内容
            if (_config.BodyHtml)
            {
                var bodybuilder = new MimeKit.BodyBuilder
                {
                    HtmlBody = body
                };
                message.Body = bodybuilder.ToMessageBody();
            }
            else
            {
                message.Body = new MimeKit.TextPart("plain")
                {
                    Text = body
                }
            };
            //添加收件人
            foreach (var item in to)
            {
                message.To.Add(new MimeKit.MailboxAddress(item, item));
            }
            //添加抄送人
            if (cc != null)
            {
                foreach (var item in cc)
                {
                    message.Cc.Add(new MimeKit.MailboxAddress(item, item));
                }
            }
            //初始化SMTP服务器并发送邮件
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect(_config.SmtpHost, _config.SmtpPort, _config.EnableSsl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(_config.SmtpAccount, _config.SmtpPwd);
                client.Send(message);
                client.Disconnect(true);
            }
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="Name">发件人名字</param>
        /// <param name="receive">接收邮箱</param>
        /// <param name="sender">发送邮箱</param>
        /// <param name="password">邮箱密码</param>
        /// <param name="host">邮箱主机</param>
        /// <param name="port">邮箱端口</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <bool> SendMailAsync(string Name, string receive, string sender, string password, string host, int port, string subject, string body)
        {
            try
            {
                          // MimeMessage代表一封电子邮件的对象
                var message = new MimeKit.MimeMessage();
                          // 添加发件人地址 Name 发件人名字 sender 发件人邮箱
                message.From.Add(new MimeKit.MailboxAddress(Name, sender));

                         // 添加收件人地址
                message.To.Add(new MimeKit.MailboxAddress("", receive));

                          // 设置邮件主题信息
                message.Subject = subject;
                          // 设置邮件内容
                var bodyBuilder = new MimeKit.BodyBuilder()
                {
                    HtmlBody = body
                };
                message.Body = bodyBuilder.ToMessageBody();
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.CheckCertificateRevocation = false;
                    //client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                    client.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto);
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(sender, password);
                    await client.SendAsync(message);

                    client.Disconnect(true);
                    return(true);
                }
            }
            catch (Exception ex)
            {
            }
            return(false);
        }
Beispiel #5
0
        /// <summary>
        /// 通过默认邮箱发送邮件
        /// </summary>
        /// <param name="subject">主题</param>
        /// <param name="htmlBody">HTML邮件体</param>
        /// <param name="toName">接收名称</param>
        /// <param name="toAddress">接收邮箱</param>
        public static void Send(string subject, string htmlBody, string toName, string toAddress)
        {
            // Mailbox Authorization Code: lmiuqpvhlnmebcfe

            // MailKit / MimeKit
            var message     = new MimeKit.MimeMessage();
            var defaultFrom = new MimeKit.MailboxAddress("Wagsn", "*****@*****.**");

            message.From.Add(defaultFrom);
            //message.To.Add(new MimeKit.MailboxAddress("2464", "*****@*****.**"));
            message.To.Add(new MimeKit.MailboxAddress(toName, toAddress));

            //message.Subject = "星期天去哪里玩?";
            message.Subject = subject;
            var bodyBuilder = new MimeKit.BodyBuilder();

            //bodyBuilder.HtmlBody = @"<h1>计划</h1><p>我想去故宫玩,如何</p>";
            //bodyBuilder.TextBody = "";
            bodyBuilder.HtmlBody = htmlBody;
            message.Body         = bodyBuilder.ToMessageBody();
            //message.Body = new TextPart("计划") { Text = "我想去故宫玩,如何" };

            using (var client2 = new MailKit.Net.Smtp.SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client2.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client2.Connect("smtp.qq.com", 587, false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client2.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client2.Authenticate("*****@*****.**", "lmiuqpvhlnmebcfe");

                client2.Send(message);
                client2.Disconnect(true);
            }
        }
Beispiel #6
0
        private MimeKit.MimeMessage Parse(EmailMessage message)
        {
            var from = MimeKit.InternetAddress.Parse(message.From);
            var to   = message.To.Select(x => MimeKit.InternetAddress.Parse(x));

            var bb = new MimeKit.BodyBuilder();

            if (message.IsBodyHtml)
            {
                bb.HtmlBody = message.Body;
            }
            else
            {
                bb.TextBody = message.Body;
            }

            foreach (var attachment in message.Attachments)
            {
                bb.Attachments.Add(attachment.Name, attachment.Content);
            }

            return(new MimeKit.MimeMessage(new[] { from }, to, message.Subject, bb.ToMessageBody()));
        }
        // https://stackoverflow.com/questions/39912942/mailkit-sendmail-doubts
        // https://stackoverflow.com/questions/37853903/can-i-send-files-via-email-using-mailkit
        public static void SendMessageComplex()
        {
            string userName  = "";
            string userPass  = "";
            string subject   = "How you doin?";
            string plainText = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
";
            string path      = @"D:\testfile.pdf";

            string host    = "smtp.gmail.com";
            int    portNum = 443;
            bool   useSsl  = false;


            MimeKit.MimeMessage message = new MimeKit.MimeMessage();
            message.From.Add(new MimeKit.MailboxAddress("Joey", "*****@*****.**"));
            message.To.Add(new MimeKit.MailboxAddress("Alice", "*****@*****.**"));

            // https://tools.ietf.org/html/rfc2076#page-16
            // https://tools.ietf.org/html/rfc1911
            // The case-insensitive values are "Personal" and "Private"
            // Normal, Confidential,

            // If a sensitivity header is present in the message, a conformant
            // system MUST prohibit the recipient from forwarding this message to
            // any other user.  If the receiving system does not support privacy and
            // the sensitivity is one of "Personal" or "Private", the message MUST
            // be returned to the sender with an appropriate error code indicating
            // that privacy could not be assured and that the message was not
            // delivered [X400].
            message.Headers.Add("Sensitivity", "Company-confidential");

            string sTime = System.DateTime.Now.AddDays(-1).ToString("dd MMM yyyy") + " " +
                           System.DateTime.Now.ToShortTimeString() + " +0100";

            // Set a message expiration date
            // When the expiration date passes, the message remains visible
            // in the message list with a strikethrough.
            // It can still be opened, but the strikethrough gives a visual clue
            // that the message is out of date or no longer relevant.
            message.Headers.Add("expiry-date", sTime);


            MailKit.DeliveryStatusNotification delivery =
                MailKit.DeliveryStatusNotification.Delay |
                MailKit.DeliveryStatusNotification.Failure |
                // MailKit.DeliveryStatusNotification.Never |
                MailKit.DeliveryStatusNotification.Success;


            message.Headers.Add(
                new MimeKit.Header(MimeKit.HeaderId.ReturnReceiptTo, "*****@*****.**")
                ); // Delivery report


            message.ReplyTo.Add(new MimeKit.MailboxAddress("Alice", "*****@*****.**"));

            message.Cc.Add(new MimeKit.MailboxAddress("Alice", "*****@*****.**"));
            message.Bcc.Add(new MimeKit.MailboxAddress("Alice", "*****@*****.**"));
            // message.Date = new System.DateTimeOffset(System.DateTime.Now);
            message.Date = System.DateTimeOffset.Now;
            //message.Attachments

            message.Importance = MimeKit.MessageImportance.High;
            message.Priority   = MimeKit.MessagePriority.Urgent;
            message.XPriority  = MimeKit.XMessagePriority.Highest;


            // message.HtmlBody
            // message.TextBody
            // message.Body
            // message.InReplyTo
            // message.MessageId
            // message.Sign();
            // message.Verify()
            // message.SignAndEncrypt();



            // Body (Mensagem)
            MimeKit.BodyBuilder bodyBuilder = new MimeKit.BodyBuilder();

            bodyBuilder.Attachments.Add(
                new MimeKit.MimePart("image", "gif")
            {
                Content = new MimeKit.MimeContent(
                    System.IO.File.OpenRead(path)
                    , MimeKit.ContentEncoding.Default
                    )
                , ContentDisposition      = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment)
                , ContentTransferEncoding = MimeKit.ContentEncoding.Base64
                , FileName = System.IO.Path.GetFileName(path)
            }
                );


            // bodyBuilder.LinkedResources.Add("fn", (byte[]) null, new MimeKit.ContentType("text", "html"));
            MimeKit.MimeEntity image = bodyBuilder.LinkedResources.Add("selfie.jpg"
                                                                       , (byte[])null
                                                                       , new MimeKit.ContentType("image", "jpeg")
                                                                       );

            image.ContentId = MimeKit.Utils.MimeUtils.GenerateMessageId();

            bodyBuilder.TextBody = "This is some plain text";
            // bodyBuilder.HtmlBody = "<b>This is some html text</b>";
            bodyBuilder.HtmlBody = string.Format(@"<p>Hey Alice,<br>
<p>What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.<br>
<p>Will you be my +1?<br>
<p>-- Joey<br>
<center><img src=""cid:{0}""></center>", image.ContentId);

            message.Subject = subject;
            message.Body    = bodyBuilder.ToMessageBody();



            // http://www.mimekit.net/docs/html/Creating-Messages.htm
            // create our message text, just like before (except don't set it as the message.Body)
            // MimeKit.MimePart body = new MimeKit.TextPart ("plain") { Text = plainText };

            // MimeKit.MimePart body = new MimeKit.TextPart("html") { Text = "<b>Test Message</b>" };



            // create an image attachment for the file located at path
            //MimeKit.MimePart attachment = new MimeKit.MimePart ("image", "gif")
            //{
            //    Content = new MimeKit.MimeContent(
            //          System.IO.File.OpenRead(path)
            //        , MimeKit.ContentEncoding.Default
            //    )
            //    ,ContentDisposition = new MimeKit.ContentDisposition (MimeKit.ContentDisposition.Attachment)
            //    ,ContentTransferEncoding = MimeKit.ContentEncoding.Base64
            //    ,FileName = System.IO.Path.GetFileName (path)
            //};

            //// now create the multipart/mixed container to hold the message text and the
            //// image attachment
            //MimeKit.Multipart multipart = new MimeKit.Multipart ("mixed");
            //multipart.Add (body);
            //multipart.Add (attachment);

            // now set the multipart/mixed as the message body
            // message.Body = multipart;

            // https://stackoverflow.com/questions/30507362/c-sharp-mailkit-delivery-status-notification
            // https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SmtpProcessReadReceipt
            // using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            using (MailKit.Net.Smtp.SmtpClient client = new SmtpClientWithStatusNotification())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(host, portNum, useSsl);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(userName, userPass);

                client.Send(message);
                client.Disconnect(true);
            } // End Using client
        }
Beispiel #8
0
        public static void SendEmail(string sToEmail, string sCcEmail, string sBCcEmail, string sSubject, string sBody, Attachment objAttachment, AlternateView objAlternateView, bool bIsHtml, System.IO.Stream attchmentFileStream, string attchmentFileName)
        {
            string SMTPClient     = ConfigurationManager.AppSettings["SMTPClient"].ToString();
            string SMTPPort       = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            bool   EnableSSL      = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"].ToString());
            string FromMail       = ConfigurationManager.AppSettings["FromMail"].ToString();
            string SmtpUserId     = ConfigurationManager.AppSettings["SmtpUserId"].ToString();
            string SmtpCredential = ConfigurationManager.AppSettings["SmtpCredential"].ToString();

            int iPort = 0;

            iPort = Convert.ToInt32(SMTPPort);

            if (iPort == 465)
            {
                try
                {
                    var client = new MailKit.Net.Smtp.SmtpClient();
                    client.Connect(SMTPClient, 465, true);

                    // Note: since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(SmtpUserId, SmtpCredential);

                    var msg = new MimeKit.MimeMessage();
                    msg.From.Add(new MimeKit.MailboxAddress(FromMail));

                    string[] ToMuliId = sToEmail.Split(',');
                    foreach (string ToEMailId in ToMuliId)
                    {
                        msg.To.Add(new MimeKit.MailboxAddress(ToEMailId));
                    }

                    if (!string.IsNullOrEmpty(sCcEmail))
                    {
                        string[] CCId = sCcEmail.Split(',');

                        foreach (string CCEmail in CCId)
                        {
                            msg.Cc.Add(new MimeKit.MailboxAddress(CCEmail));
                        }
                    }

                    if (!string.IsNullOrEmpty(sBCcEmail))
                    {
                        string[] bccid = sBCcEmail.Split(',');

                        foreach (string bccEmailId in bccid)
                        {
                            msg.Bcc.Add(new MimeKit.MailboxAddress(bccEmailId));
                        }
                    }

                    var builder = new MimeKit.BodyBuilder();
                    msg.Subject = sSubject;

                    if (bIsHtml)
                    {
                        builder.HtmlBody = sBody;
                    }
                    else
                    {
                        builder.TextBody = sBody;
                    }

                    if (objAttachment != null)
                    {
                        builder.Attachments.Add(attchmentFileName, attchmentFileStream);
                    }

                    // Now we just need to set the message body and we're done
                    msg.Body = builder.ToMessageBody();

                    client.Send(msg);
                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                    //LogError("An error occurred while [SendEmail] : " + ex.Message.ToString() + " " + ex.StackTrace, "", "SendEmail");
                    throw ex;
                }
            }
            else  //For non 465 ports
            {
                SmtpClient  objSmtpClient  = null;
                MailMessage objMailMessage = null;
                try
                {
                    objSmtpClient = new SmtpClient(SMTPClient);

                    if (iPort == 25)
                    {
                        objSmtpClient.EnableSsl             = false;
                        objSmtpClient.UseDefaultCredentials = true;
                    }
                    else
                    {
                        objSmtpClient.EnableSsl = EnableSSL;
                        if (iPort != 0)
                        {
                            objSmtpClient.Port = iPort;
                        }

                        if (SmtpCredential != "")
                        {
                            objSmtpClient.Credentials = new System.Net.NetworkCredential(SmtpUserId, SmtpCredential);
                        }
                        else
                        {
                            objSmtpClient.UseDefaultCredentials = true;
                        }
                    }
                    objMailMessage = new MailMessage();
                    string[] ToMuliId = sToEmail.Split(',');
                    foreach (string ToEMailId in ToMuliId)
                    {
                        objMailMessage.To.Add(new MailAddress(ToEMailId)); //adding multiple TO Email Id
                    }

                    if (sCcEmail != "")
                    {
                        string[] CCId = sCcEmail.Split(',');

                        foreach (string CCEmail in CCId)
                        {
                            objMailMessage.CC.Add(new MailAddress(CCEmail)); //Adding Multiple CC email Id
                        }
                    }

                    if (sBCcEmail != "")
                    {
                        string[] bccid = sBCcEmail.Split(',');

                        foreach (string bccEmailId in bccid)
                        {
                            objMailMessage.Bcc.Add(new MailAddress(bccEmailId)); //Adding Multiple BCC email Id
                        }
                    }
                    //if (iPort != 25)
                    //{
                    MailAddress MailFrom = new MailAddress(FromMail);
                    objMailMessage.From = MailFrom;
                    //}
                    //else
                    //{
                    //    MailAddress MailFrom = new MailAddress();

                    //    MailFrom.DisplayName =
                    //    objMailMessage.From = MailFrom;
                    //}
                    objMailMessage.Subject    = sSubject;
                    objMailMessage.IsBodyHtml = bIsHtml;
                    if (objAlternateView == null)
                    {
                        objMailMessage.Body = sBody;
                    }
                    else
                    {
                        objMailMessage.AlternateViews.Add(objAlternateView);
                    }
                    if (objAttachment != null)
                    {
                        objMailMessage.Attachments.Add(objAttachment);
                    }

                    objSmtpClient.Send(objMailMessage);
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                    //LogError("An error occurred while [SendEmail] : " + ex.Message.ToString() + " " + ex.StackTrace, "", "SendEmail");
                    throw ex;
                }
                finally
                {
                    if (objMailMessage != null)
                    {
                        objMailMessage.Dispose();
                    }
                }
            }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            // Mailbox Authorization Code: lmiuqpvhlnmebcfe

            // MailKit / MimeKit
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MimeKit.MailboxAddress("Wagsn", "*****@*****.**"));
            message.To.Add(new MimeKit.MailboxAddress("2464", "*****@*****.**"));

            message.Subject = "星期天去哪里玩?";
            var bodyBuilder = new MimeKit.BodyBuilder();

            //bodyBuilder.HtmlBody = @"<h1>计划</h1><p>我想去故宫玩,如何</p>";
            bodyBuilder.HtmlBody = "计划\r\n我想去故宫玩,如何";
            message.Body         = bodyBuilder.ToMessageBody();
            //message.Body = new TextPart("计划") { Text = "我想去故宫玩,如何" };

            using (var client2 = new MailKit.Net.Smtp.SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client2.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client2.Connect("smtp.qq.com", 587, false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client2.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client2.Authenticate("*****@*****.**", "lmiuqpvhlnmebcfe");

                client2.Send(message);
                client2.Disconnect(true);
            }

            //System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            //mailMessage.From = new System.Net.Mail.MailAddress("*****@*****.**", "Wagsn");
            //mailMessage.To.Add(new System.Net.Mail.MailAddress("*****@*****.**"));
            ////var bodyBuilder = new BodyBuilder();
            ////mailMessage.To.Add(new MailAddress("*****@*****.**"));
            //mailMessage.Subject = ".NET Core 邮件发送测试";
            ////mailMessage.Body = "纯文本测试第一行\r\n纯文本测试第二行";
            //mailMessage.Body = "<h1>富文本标题</h1><p>富文本正文</p>";
            //mailMessage.IsBodyHtml = true;

            //System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            //client.Host = "smtp.qq.com";
            //client.Port = 587;
            //client.EnableSsl = true;
            //client.Credentials = new NetworkCredential("*****@*****.**", "lmiuqpvhlnmebcfe");

            //try
            //{
            //    client.Send(mailMessage);
            //}
            //catch(Exception e)
            //{
            //    Console.Error.WriteLine($"Error: {e}");
            //}

            System.Console.WriteLine("邮件已发送");
            System.Console.ReadKey();
        }
Beispiel #10
0
        /// <summary>
        /// 이메일 전송 - MimeKit 설치
        /// </summary>
        /// <param name="SMTP_host" > SMTP주소 구글(smtp.gmail.com)_네이버(smtp.naver.com)_메일플러그(smtp.mailplug.co.kr)</param>
        /// <param name="SMTP_mail" > 메일 접속 아이디 (예[email protected])</param>
        /// <param name="SMTP_pw"   > 메일 접속 암호                </param>
        /// <param name="SMTP_port" > SMTP주소 구글(465,587)_네이버(465)_메일플러그(465)</param>
        /// <param name="from_name" > 송신자 (예-신짱구)            </param>
        /// <param name="to_mail"   > 수신 메일 (예[email protected])  </param>
        /// <param name="title"     > 메일 제목                     </param>
        /// <param name="content"   > 메일 내용                     </param>
        /// <param name="files"     > 첨부 파일 경로                </param>
        /// <param name="isHtmlBody"> HTML로 작성된 메일 내용       </param>
        public static async System.Threading.Tasks.Task SendMail(string SMTP_host,
                                                                 string SMTP_mail,
                                                                 string SMTP_pw,
                                                                 int SMTP_port,
                                                                 string from_name,
                                                                 List <string> to_mail,
                                                                 string subject,
                                                                 string content,
                                                                 string[] files  = null,
                                                                 bool isHtmlBody = false)
        {
            try
            {
                int MAX_MAIL_COUNT = 100;
                int loop           = to_mail.Count / MAX_MAIL_COUNT;
                for (int i = 0; loop >= i; i++)
                {
                    MimeKit.MimeMessage message = new MimeKit.MimeMessage();
                    MimeKit.BodyBuilder body    = new MimeKit.BodyBuilder();


                    message.From.Add(new MimeKit.MailboxAddress(from_name, SMTP_mail));             //----- 메일 송신자
                    for (int mail_i = i * MAX_MAIL_COUNT; mail_i < (i * MAX_MAIL_COUNT) + MAX_MAIL_COUNT && mail_i < to_mail.Count; mail_i++)
                    {
                        message.To.Add(new MimeKit.MailboxAddress("", to_mail[mail_i]));            //----- 메일 수신자
                    }
                    message.Subject = subject;                                                      //----- 메일 제목
                    if (isHtmlBody == true)
                    {
                        body.HtmlBody = content;
                    }
                    else
                    {
                        body.TextBody = content;
                    }

                    #region 첨부파일
                    if (files != null)
                    {
                        foreach (string filePath in files)
                        {
                            if (filePath.Length < 1)
                            {
                                continue;
                            }

                            try
                            {
                                System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
                                if (fi.Exists == true)
                                {
                                    //파일 불러오기
                                    byte[] fileBytes = StreamToBytes(System.IO.File.OpenRead(filePath));

                                    //파일 첨부
                                    body.Attachments.Add(fi.Name, fileBytes);
                                }
                            }
                            catch (System.ArgumentException e)
                            {
                                System.Console.WriteLine("");
                                System.Console.WriteLine("===== 잘못된 파일 경로 : " + filePath + " =====");
                                System.Console.WriteLine("");
                            }
                        }
                    }
                    #endregion
                    message.Body = body.ToMessageBody();                                            //----- 메일 내용

                    using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
                    {
                        client.ServerCertificateValidationCallback = (object sender,
                                                                      X509Certificate certificate,
                                                                      X509Chain chain,
                                                                      System.Net.Security.SslPolicyErrors sslPolicyErrors) => true;
                        await client.ConnectAsync(SMTP_host, SMTP_port, true);                      //----- SMTP 호스트 주소 / 포트 / SSL 사용

                        await client.AuthenticateAsync(SMTP_mail, SMTP_pw);                         //----- SMTP 계정

                        client.Capabilities.HasFlag(MailKit.Net.Smtp.SmtpCapabilities.StartTLS);    //----- TLS
                        await client.SendAsync(message);                                            //----- 메일 전송

                        await client.DisconnectAsync(true);                                         //----- 연결 해제
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #11
0
        private async Task <bool> SendMailkit(
            string from,
            string to,
            string subject,
            string body,
            string mailServerAddress,
            int mailServerPort,
            string userId,
            string userPassword,
            IEnumerable <string> attachments     = null,
            IEnumerable <string> attachmentNames = null,
            string fromName = null,
            string cc       = null,
            string bcc      = null,
            bool useSSL     = false,
            bool useTLS     = false)
        {
            MimeKit.MimeMessage oMsg = new MimeKit.MimeMessage();
            try
            {
                if (string.IsNullOrWhiteSpace(from))
                {
                    new Exception("No sender");
                }

                //Imposta il mittente
                oMsg.From.Add(new MimeKit.MailboxAddress(fromName, from));

                //Imposta i TO
                if (!string.IsNullOrWhiteSpace(to) && to.IndexOf(";") >= 0)
                {
                    foreach (string eml in to.Split(';').Where(t => !string.IsNullOrWhiteSpace(t)).Distinct())
                    {
                        oMsg.To.Add(new MimeKit.MailboxAddress(eml.Replace(" ", ""), eml.Replace(" ", "")));
                    }
                }
                else if (!string.IsNullOrWhiteSpace(to))
                {
                    oMsg.To.Add(new MimeKit.MailboxAddress(to.Replace(" ", ""), to.Replace(" ", "")));
                }
                else
                {
                    throw new Exception("No recipients"); //Se non c'è nessun destinatario lancio un'eccezione
                }
                //Imposta a CC
                if (!string.IsNullOrWhiteSpace(cc) && cc.IndexOf(";") >= 0)
                {
                    foreach (string eml in cc.Split(';').Where(t => !string.IsNullOrWhiteSpace(t)).Distinct())
                    {
                        oMsg.Cc.Add(new MimeKit.MailboxAddress(eml.Replace(" ", ""), eml.Replace(" ", "")));
                    }
                }
                else if (!string.IsNullOrWhiteSpace(cc))
                {
                    oMsg.Cc.Add(new MimeKit.MailboxAddress(cc.Replace(" ", ""), cc.Replace(" ", "")));
                }

                //Imposta i BCC
                if (!string.IsNullOrWhiteSpace(bcc) && bcc.IndexOf(";") >= 0)
                {
                    foreach (string eml in bcc.Split(';').Where(t => !string.IsNullOrWhiteSpace(t)).Distinct())
                    {
                        oMsg.Bcc.Add(new MimeKit.MailboxAddress(eml.Replace(" ", ""), eml.Replace(" ", "")));
                    }
                }
                else if (!string.IsNullOrWhiteSpace(bcc))
                {
                    oMsg.Bcc.Add(new MimeKit.MailboxAddress(bcc.Replace(" ", ""), bcc.Replace(" ", "")));
                }

                //Imposto oggetto
                oMsg.Subject = subject;

                //Imposto contenuto
                var builder = new MimeKit.BodyBuilder
                {
                    HtmlBody = body
                };

                //imposto gli allegati
                if (attachments?.Count() > 0)
                {
                    foreach (string all in attachments)
                    {
                        if (!string.IsNullOrWhiteSpace(all))
                        {
                            builder.Attachments.Add(all);
                        }
                    }
                }

                //rename allegati
                for (int attIndex = 0; attIndex < builder.Attachments.Count; attIndex++)
                {
                    if (builder.Attachments[attIndex].IsAttachment && attachmentNames?.Count() > attIndex)
                    {
                        builder.Attachments[attIndex].ContentDisposition.FileName = attachmentNames.ElementAt(attIndex);
                    }
                }

                oMsg.Body = builder.ToMessageBody();

                _logger.LogInformation($"{nameof(IEmailService)}.{nameof(SendMailkit)} ==== from {string.Join(";", oMsg.From.Select(t => t.ToString()))} - to {string.Join(";", oMsg.To.Select(t => t.ToString()))} - cc {string.Join(";", oMsg.Cc.Select(t => t.ToString()))} - bcc {string.Join(";", oMsg.Bcc.Select(t => t.ToString()))} ==== subject '{subject}'");

                //Imposto il Server Smtp
                //Metto valori di default da web.config nel caso si passi SmtpClient Nothing
                MailKit.Net.Smtp.SmtpClient client;
                try
                {
                    client = new MailKit.Net.Smtp.SmtpClient();
                    await client
                    .ConnectAsync(
                        mailServerAddress,
                        mailServerPort,
                        useTLS?
                        MailKit.Security.SecureSocketOptions.StartTls:
                        (useSSL ?
                         MailKit.Security.SecureSocketOptions.SslOnConnect :
                         MailKit.Security.SecureSocketOptions.None))
                    .ConfigureAwait(false);
                }
                catch (MailKit.Security.AuthenticationException ex)
                {
                    if (ex.InnerException is System.ComponentModel.Win32Exception)
                    {
                        //Fix per gestione bug .net framework / mailkit
                        //https://github.com/dotnet/corefx/issues/1854#issuecomment-160513245
                        client = new MailKit.Net.Smtp.SmtpClient();
                        await client
                        .ConnectAsync(
                            mailServerAddress,
                            mailServerPort,
                            useTLS?
                            MailKit.Security.SecureSocketOptions.StartTls:
                            (useSSL ?
                             MailKit.Security.SecureSocketOptions.SslOnConnect :
                             MailKit.Security.SecureSocketOptions.None))
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        throw;
                    }
                }

                using (client)
                {
                    try
                    {
                        // Note: since we don't have an OAuth2 token, disable
                        // the XOAUTH2 authentication mechanism.
                        client.AuthenticationMechanisms.Remove("XOAUTH2");

                        // Note: only needed if the SMTP server requires authentication
                        if (!string.IsNullOrEmpty(userPassword))
                        {
                            await client.AuthenticateAsync(userId, userPassword);
                        }
                        await client.SendAsync(oMsg).ConfigureAwait(false);
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        await client.DisconnectAsync(true).ConfigureAwait(false);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError($"{nameof(IEmailService)}.{nameof(SendMailkit)} FATAL EXCEPTION: {ex.Message}", ex);
                throw ex;
            }
            finally { oMsg = null; }
        }
Beispiel #12
0
        public static void SendEmail(string sToEmail, string sCcEmail, string sBCcEmail, string sSubject, string sBody, Attachment objAttachment, AlternateView objAlternateView, bool bIsHtml, System.IO.Stream attchmentFileStream, string attchmentFileName)
        {
            int    iPort          = 0;
            string SMTPPort       = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            string SMTPClient     = ConfigurationManager.AppSettings["SMTPClient"].ToString();
            bool   EnableSSL      = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"].ToString());
            string FromMail       = ConfigurationManager.AppSettings["FromMail"].ToString();
            string SmtpUserId     = ConfigurationManager.AppSettings["SmtpUserId"].ToString();
            string SmtpCredential = ConfigurationManager.AppSettings["SmtpCredential"].ToString();

            iPort = Convert.ToInt32(SMTPPort);

#if DEBUG
            //iPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort_Test"].ToString());
            //SMTPClient = ConfigurationManager.AppSettings["SMTPClient_Test"].ToString();
            //EnableSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"].ToString());
            //FromMail = ConfigurationManager.AppSettings["FromMail_Test"].ToString();
            //SmtpCredential = ConfigurationManager.AppSettings["SmtpCredential_Test"].ToString();
#endif


            if (iPort == 465)
            {
                try
                {
                    var client = new MailKit.Net.Smtp.SmtpClient();
                    client.Connect(SMTPClient, 465, true);

                    // Note: since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(SmtpUserId, SmtpCredential);

                    var msg = new MimeKit.MimeMessage();
                    msg.From.Add(new MimeKit.MailboxAddress(FromMail));

                    string[] ToMuliId = sToEmail.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

                    foreach (string ToEMailId in ToMuliId)
                    {
                        msg.To.Add(new MimeKit.MailboxAddress(ToEMailId));
                    }

                    if (!string.IsNullOrEmpty(sCcEmail))
                    {
                        string[] CCId = sCcEmail.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();;

                        foreach (string CCEmail in CCId)
                        {
                            msg.Cc.Add(new MimeKit.MailboxAddress(CCEmail));
                        }
                    }

                    if (!string.IsNullOrEmpty(sBCcEmail))
                    {
                        string[] bccid = sBCcEmail.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();;

                        foreach (string bccEmailId in bccid)
                        {
                            msg.Bcc.Add(new MimeKit.MailboxAddress(bccEmailId));
                        }
                    }

                    var builder = new MimeKit.BodyBuilder();
                    msg.Subject = sSubject;

                    if (bIsHtml)
                    {
                        //builder.HtmlBody = string.Format(sBody);
                        builder.HtmlBody = sBody;
                    }
                    else
                    {
                        builder.TextBody = sBody;
                    }

                    //if (objAttachment != null)
                    //{
                    //    builder.Attachments.Add(@"C:\Users\Joey\Documents\party.ics");
                    //}
                    if (objAttachment != null)
                    {
                        builder.Attachments.Add(attchmentFileName, attchmentFileStream);
                    }

                    // Now we just need to set the message body and we're done
                    msg.Body = builder.ToMessageBody();

                    client.Send(msg);
                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                    SendEmailTest("[email protected],[email protected]", "", "", "Error", ex.ToString() + "Message:: " + ex.Message, null, null, true);
                    //LogError("An error occurred while [SendEmail] : " + ex.Message.ToString() + " " + ex.StackTrace, "", "SendEmail");
                    throw ex;
                }
            }
            else  //For non 465 ports
            {
                SmtpClient  objSmtpClient = null;
                MailMessage mailMessage   = null;

                try
                {
                    objSmtpClient = new SmtpClient(SMTPClient);

                    if (iPort == 25)
                    {
                        objSmtpClient.EnableSsl             = false;
                        objSmtpClient.UseDefaultCredentials = true;
                    }
                    else
                    {
                        objSmtpClient.EnableSsl = EnableSSL;
                        if (iPort != 0)
                        {
                            objSmtpClient.Port = iPort;
                        }

                        if (SmtpCredential != "")
                        {
                            objSmtpClient.Credentials = new System.Net.NetworkCredential(SmtpUserId, SmtpCredential);
                        }
                        else
                        {
                            objSmtpClient.UseDefaultCredentials = true;
                        }
                    }
                    mailMessage = new MailMessage();
                    string[] ToMuliId = sToEmail.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();;
                    foreach (string ToEMailId in ToMuliId)
                    {
                        mailMessage.To.Add(new MailAddress(ToEMailId));
                    }

                    if (!string.IsNullOrEmpty(sCcEmail))
                    {
                        string[] CCId = sCcEmail.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();;

                        foreach (string CCEmail in CCId)
                        {
                            mailMessage.CC.Add(new MailAddress(CCEmail));
                        }
                    }

                    if (!string.IsNullOrEmpty(sBCcEmail))
                    {
                        string[] bccid = sBCcEmail.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();;

                        foreach (string bccEmailId in bccid)
                        {
                            mailMessage.Bcc.Add(new MailAddress(bccEmailId));
                        }
                    }

                    MailAddress MailFrom = new MailAddress(FromMail);
                    mailMessage.From       = MailFrom;
                    mailMessage.Subject    = sSubject;
                    mailMessage.IsBodyHtml = bIsHtml;
                    if (objAlternateView == null)
                    {
                        mailMessage.Body = sBody;
                    }
                    else
                    {
                        mailMessage.AlternateViews.Add(objAlternateView);
                    }
                    if (objAttachment != null)
                    {
                        mailMessage.Attachments.Add(objAttachment);
                    }

                    objSmtpClient.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    SendEmailTest("[email protected],[email protected]", "", "", "Error", ex.ToString() + "Message:: " + ex.Message, null, null, true);
                    throw ex;
                }
                finally
                {
                    if (mailMessage != null)
                    {
                        mailMessage.Dispose();
                    }
                }
            }
        }