C# 发邮件

date
Jan 15, 2022
slug
10015
status
Published
tags
C#
summary
type
Post
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SmtpClient mySmtpClient = new("192.168.100.204")
                {
                    // mySmtpClient.Port = 465;
                    //mySmtpClient.EnableSsl = true;
                    // set smtp-client with basicAuthentication
                    UseDefaultCredentials = false
                };
                var basicAuthenticationInfo = new NetworkCredential("geo@prospector.bgp", "123456");
                mySmtpClient.Credentials = basicAuthenticationInfo;

                // add from,to mailaddresses
                var from = new MailAddress("geo@prospector.bgp");
                var to = new MailAddress("geo@prospector.bgp");
                MailMessage myMail = new(from, to);
               // myMail.To.Add(new MailAddress("navigator@prospector.bgp"));
               //myMail.To.Add(new MailAddress("geo@prospector.bgp"));
                // add ReplyTo
                // MailAddress replyTo = new MailAddress("reply@example.com");
                // myMail.ReplyToList.Add(replyTo);

                // set subject and encoding
                myMail.Subject = "C# Test message";
                myMail.SubjectEncoding = System.Text.Encoding.UTF8;

                // set body-message and encoding
                myMail.Body = "Test Mail using C#.";
                myMail.BodyEncoding = System.Text.Encoding.UTF8;
                // text or html
                myMail.IsBodyHtml = false;
                mySmtpClient.Send(myMail);
            }

            catch (SmtpException ex)
            {
                throw new ApplicationException
                  ("SmtpException has occured: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

© Wen Bo 2021 - 2022