我可以使用哪些对象和功能发送电子邮件?

时间:2011-05-10 05:18:37

标签: c# asp.net email

        MailMessage mail = new MailMessage();

    mail.To.Add("makovetskiyd@yahoo.co.uk");

    mail.From = new MailAddress("makovetskiyd@yahoo.co.uk");

    mail.Subject = "Test Email";

    string Body = "Welcome to CodeDigest.Com!!";

    mail.Body = Body;

    SmtpClient smtp = new SmtpClient();

    smtp.Host = ConfigurationManager.AppSettings["SMTP"];//i get nuller point exception here.. what does the class configuration manager do?

    smtp.Send(mail);

2 个答案:

答案 0 :(得分:1)

您可以使用Microsoft的内置类(System.Net.Mail)。例如,这是一种快速简便的发送电子邮件的方法:

public static void SendEmail(string messageText, string subjectText,
        string fromAddress, string toAddress, string ccAddress,
        string bccAddress, string hostName, string attachments,
        string userName, string password)
    {
        try
        {
        string[] toAddressList = toAddress.Split(';');
        string[] ccAddressList = ccAddress.Split(';');
        string[] bccAddressList = bccAddress.Split(';');
        string[] attachmentList = attachments.Split(';');

        MailMessage mail = new MailMessage();

        //Loads the To address field
        foreach (string address in toAddressList)
        {
            if (address.Length > 0)
            {
                mail.To.Add(address);
            }
        }

            //Loads the CC address field
            foreach (string address in ccAddressList)
            {
                if (address.Length > 0)
                {
                    mail.CC.Add(address);
                }
            }

            //Loads the BCC address field
            foreach (string address in bccAddressList)
            {
                if (address.Length > 0)
                {
                    mail.Bcc.Add(address);
                }
            }

            //Loads the attachment list
            foreach (string attachment in attachmentList)
            {
                if (attachment.Length > 0)
                {
                    mail.Attachments.Add(new Attachment(attachment));
                }
            }

            mail.From = new MailAddress(fromAddress);
            mail.Subject = subjectText;
            string Body = messageText;
            mail.Body = Body;

            SmtpClient smtp = new SmtpClient();
            smtp.Host = hostName;
            smtp.Credentials = new System.Net.NetworkCredential(userName,password);
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.Send(mail);

            mail.Dispose();
            smtp.Dispose();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

在此示例中,您可以通过Gmail发送电子邮件。

答案 1 :(得分:0)

您可以使用System.Net.Mail类。

以下是使用gmail进行操作的示例:Sending email in .NET through Gmail