1. 程式人生 > 其它 >C#阿里境外伺服器部署企業郵箱發郵件程式碼

C#阿里境外伺服器部署企業郵箱發郵件程式碼

 static string accountName = "發件人郵箱";

        static string password = "發件人郵箱密碼";
        static string smtpServer = "smtp.qiye.aliyun.com";
        static int smtpPort = 80;
        static string displayName = "發件人顯示";
        //static string userState = System.Configuration.ConfigurationManager.AppSettings["mailUserState"];

        static public void SendMail(string sendTo, string emailCC, string strsubject, string strbody)
        {
            try
            {
                Console.WriteLine("傳送中…………");
                // Command line argument must the the SMTP host.
                SmtpClient client = new SmtpClient(smtpServer, smtpPort);
                client.UseDefaultCredentials = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Credentials = new NetworkCredential(accountName, password);

                // Specify the e-mail sender.
                // Create a mailing address that includes a UTF8 character
                // in the display name.
                MailAddress from = new MailAddress(accountName,
                   displayName,
                System.Text.Encoding.UTF8);
                // Set destinations for the e-mail message.
                MailAddress to = new MailAddress(sendTo);
                // Specify the message content.
                MailMessage message = new MailMessage(from, to);
                if (!string.IsNullOrEmpty(emailCC))
                {
                    message.CC.Add(emailCC);
                }

                message.Body = strbody;
                // Include some non-ASCII characters in body and subject.
                string someArrows = "(請勿回覆這封郵件)";
                message.Body += Environment.NewLine + someArrows;
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = strsubject;
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                message.Priority = MailPriority.High;
                message.IsBodyHtml = true;
                client.Send(message);
                message.Dispose();
                client.Dispose();
                Console.WriteLine("成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine("失敗");
                Console.WriteLine(ex.InnerException.ToString());
            }
        }