コード例 #1
0
ファイル: MailSender.cs プロジェクト: furena/bigcatAlpha
        public static void SendMessage(string sendTo, string subject, string body, string replyTo = "", string sendCc = "", bool sendAsHtml = true)
        {
            var    staticbody    = body;
            string formattedBody = "";

            if (sendAsHtml)
            {
                body          = body.Replace("  ", "  ");
                body          = body.Replace(Environment.NewLine, "<br>");
                formattedBody = MailTemplate.Replace("{{subject}}", subject);
                formattedBody = formattedBody.Replace("{{body}}", body);
            }

            try
            {
                var msg = new MailMessage
                {
                    From       = new MailAddress(MailFrom),
                    Body       = ((sendAsHtml) ? formattedBody : staticbody),
                    IsBodyHtml = sendAsHtml,
                    Subject    = subject
                };

                bool isAddressed = false;
                if (sendTo.Length > 0)
                {
                    isAddressed = true;
                    msg.To.Add(sendTo);
                }
                if (sendCc.Length > 0)
                {
                    isAddressed = true;
                    msg.CC.Add(sendCc);
                }
                if (!isAddressed)
                {
                    return;
                }

                if (replyTo.Length > 0)
                {
                    msg.ReplyToList.Add(replyTo);
                }
                if (sendAsHtml)
                {
                    if (Logo != null && Logo.Length > 0 && formattedBody.IndexOf("cid:") > 0)
                    {
                        var oRes = new LinkedResource(new MemoryStream(Logo), "image/png")
                        {
                            ContentId = "logo.png"
                        };
                        formattedBody = formattedBody.Replace("cid:", "cid:logo.png");
                        var oView = AlternateView.CreateAlternateViewFromString(formattedBody, new System.Net.Mime.ContentType("text/html"));
                        oView.LinkedResources.Add(oRes);
                        msg.AlternateViews.Add(oView);
                    }
                }
                SendMessage(msg);
            }
            catch (Exception ex)
            {
                throw new Exception("SendMessage failed: " + ex.Message, ex);
            }
        }