Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sending Email In 2.0 c#

Status
Not open for further replies.

adamroof

Programmer
Nov 5, 2003
1,107
US
How to send an email using the new System.Net.Mail

I searched this forum for this issue, and only found 2 posts, one which i responded to a while ago before i started using 2.0, and i didnt answer my own question!

My question was using the default credential supplied in the web config from my codebehind. I had to reinitialize the credentials in code until i found the client.UseDefaultCredentials = true setting.

This new version is easier to use, so you may all have it figured out already, but for those that are still slightly confused as i was, hopefully this will help.

web.config section
Code:
  <system.net>
    <mailSettings>
      <smtp from="sales@domainname.com" deliveryMethod="Network">
        <network host="mail.domainname.com" port="25" userName="sales@domainname.com" password="nottellingyou" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>

code behind
Code:
//dont forget these
...

using System.Net
using System.Net.Mail

...
    public void sendEmail(object sender, EventArgs e)
    {
        string From = "me@domainname.com";
        string fromName = "Silly Website"; //set email display name
        string Subject = "Web Site Question Submitted";
        string body = "<font style='font-family:arial;font-size:9pt;'";
        body += " From: " + txtReqName.Text + "<br>"
                + "Email: " + txtReqEmail.Text + "<br>"
                + "Question: " + txtQuestion.Text;
        body += "</font>";

        sendEmails(From, fromName, From, Subject, body);
    }

    public void sendEmails(string from, string fromName, string to, string subj, string body)
    {
        MailMessage mailMsg = new MailMessage();
        mailMsg.From = new MailAddress(from, fromName);
        mailMsg.To.Add(new MailAddress(to));
        mailMsg.Subject = subj;
        mailMsg.Body = body;
        mailMsg.IsBodyHtml = true;
        SmtpClient client = new SmtpClient();

        try
        {
            client.UseDefaultCredentials = true;
            client.Send(mailMsg);
        }
        catch (Exception ex)
        {
            lblMessage.Text += ex.Message;
        }
    }
 
CORRECTION!

sorry...my err message wasnt showing correct, i get the email to myself because my webserver hosts my email, non-local emails require auth, and was failing...credentials should be set to FALSE.

should be this
Code:
  <system.net>
    <mailSettings>
      <smtp from="sales@domainname.com" deliveryMethod="Network">
        <network host="mail.domainname.com" port="25" userName="sales@domainname.com" password="stongpasswordhere" [b]defaultCredentials="false"[/b] />
      </smtp>
    </mailSettings>
  </system.net>

and heres all i need to use the web.config settings
Code:
        try
        {
            SmtpClient client = new SmtpClient();
            client.Send(mailMsg);
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }

sorry about this mis information, wish i could edit my post
 
Can i ask what this bit does:
<smtp from="sales@domainname.com"...
if the mail message specifically sets the From address i.e.
Code:
mailMsg.From = new MailAddress(from, fromName);
Which from address is actually used and if one overrides the other why are two set (or am I mis-understanding what you are doing?).



____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 

hello,

If set to true, the "UseDefaultCredntials" property does not automatically retrieve authentication credentials from the included web.config or app.config file (ie. you have to create functions to retrieve the XML attributes from file.)
All it does is tell the smtpclient to not use authentication

take the smtpClient object and set the following properties - in your try catch statement include:

client.Host = "enter your outbound smtp host here once read from file";
client.Port = 25; // I think the default port is 25 but set it anyway.

Alternatively, you can use the smtp object declaration constructors as such:

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(Host, Port);


If you need authentication (ie. you use username and password and even SSL when sending) you need to create a NetworkCredientials object.

client.UseDefaultCredentials = false; // Set to true if no authentication is neccessary.

client.Credentials = new System.Net.Mail.NetworkCredentials(username, password);

or Instantiate the object first then set it to the SmtpClient object.

For SSL
client.SSL = false; // Use accordingly

your sender address does not need to match the smtp domain.

If you have used the System.Web.Mail smtp object in SDK v1.1, you will notice the improvements in the mail message properties (ie. To, From etc...) Hope this helps

:)
 
c8 -
in my scenario, the smtp from in the config would be the default from if none specified, i dynamically use different from addresses depending on user selection in code. And i get to use the included display name feature of 2.0! I was just snippeting my code, but i guess that would confuse some. Ive updated below.

boot -
excellent info, ive read the msdn on this, but couldnt properly disseminate the related info for my usage, great summary, thanks. I was using the client.Credentials = new... earlier, but if its set in the config file, setting defaultCredentials to false, there was no need to reinitialize the credentials in codebehind, nor the host and port. My previous follow up corrective post is all thats needed.

Overall - System.Net.Mail is much easier and more functional!

Code:
    public void sendEmail(object sender, EventArgs e)
    {
        string from = rbQuestionFor.SelectedItem.Value + "@domainname.com";
        string fromName = "Silly Website " + rbQuestionFor.SelectedItem.Text;
        string subject = "Silly Website Contact Request";
        string body = "<font style='font-family:arial;font-size:9pt;'>"
                + "Thank you for contacting Silly Website. The details of the request follows."
                + "<br>We will attempt to respond as soon as possible.<br><br><strong>Request:</strong><br>"
                + "Reply Via: " + rbToContact.SelectedItem.Text + "<br>"
                + "From: " + contactInfo(txtReqName.Text) + "<br>"
                + "Email: " + contactInfo(txtReqEmail.Text) + "<br>"
                + "Phone: " + contactInfo(txtReqPhone.Text) + "<br>"
                + "Question For: " + rbQuestionFor.SelectedItem.Text + "<br>"
                + "<b>Question:</b><br> " + contactInfo(txtReqQuestion.Text)
                + "</font>";

        try
        {
            //send the requestor an email
            sendEmails(from, fromName, from, txtReqEmail.Text, subject, body);
            //change Reply To Address for the email sent to Support
            sendEmails(from, fromName, txtReqEmail.Text, from, subject, body);
        }
        catch (Exception ex)
        {
            auditErr("sendEmail", ex.Message);
        }
    }

    public void sendEmails(string from, string fromName, string replyTo, string to, string subj, string body)
    {
        MailMessage mailMsg = new MailMessage();
        mailMsg.From = new MailAddress(from, fromName);
        mailMsg.ReplyTo = new MailAddress(replyTo);
        mailMsg.To.Add(new MailAddress(to));
        mailMsg.Subject = subj;
        mailMsg.Body = body;
        mailMsg.IsBodyHtml = true;

        try
        {
            SmtpClient client = new SmtpClient();
            client.Send(mailMsg);
        }
        catch (Exception ex)
        {
            auditErr("sendEmails", ex.Message);
        }
    }

    public string contactInfo(string val)
    {
        if (val.Length > 0)
        {
            return val.Replace("\n", "<br>");
        }
        else
        {
            return "Not Specified";
        }
    }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top