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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help modifying email code 2

Status
Not open for further replies.

aspdotnetuser

Programmer
Oct 10, 2008
45
GB
Hi,

Any comments and suggestions will be appreciated! :)

I currently have the following send email code hard coded into a .cs file, it uses System.Web.Mail but will use the more updated methods later.

[blue]MailMessage email = new MailMessage();
email.To = "emailaddress@email.com";
email.From = "do_not_reply@email.com";
email.BodyFormat = MailFormat.Html;
email.Subject = "Test email";
email.Body ="Test email";[/blue]
try
{
SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"].ToString();
SmtpMail.Send(email);
}
catch
{}


What would I use instead of the code in try{} (in red) if I had the SMTP settings setup in web.config within the System.Net tag?

Sorry if my question isn't very clear!
 
the 2 are mutually exclusive. If you use then System.Net node in the web config then you don't need to set the server, port, or sender address. you can also use this to configure how to send email, which is good for testing vs. production.

swallowing exceptions is considered a bad practice. at a minimum you should log it using a logging library.
Code:
try
{
   MailMessage email = new MailMessage();
   email.To = "emailaddress@email.com";
   email.BodyFormat = MailFormat.Html;
   email.Subject = "Test email";
   email.Body ="Test email";

   new SmtpClient().Send(email);  
}
catch(SmtpException exception)
{
   Log.Error(exception);
}
Code:
<system.net>
   <mailSettings>
      <smpt from="do_not_reply@email.com" ... other properties>
         <network host="email server" ... other properties />
      </smpt>
   </mailSettings>
<system.net>

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
In your web.config
Code:
  <system.net>
    <mailSettings>
      <smtp from="adamr@domain.com" deliveryMethod="Network">
        <network host="mail.domain.com" port="25" defaultCredentials="false" />
      </smtp>
    </mailSettings>
  </system.net>

In your .cs file
Code:
    try
    {
        SmtpClient client = new SmtpClient();
        client.Send(email); //the variable email = your MailMessage
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }


Heres one code i use to include most of the features. It uses the feature to create the html email AND the text only email automagically! And a regex email validator.
Code:
public void sendEmail(string from, string fromName, string to, string cc, string bcc, string subj, string BodyText, string Attachments)
{
    MailMessage mailMsg = new MailMessage();
    mailMsg.From = new MailAddress(from, fromName);

    #region Email Addressing
    string[] emailTo = to.Replace(" ", "").Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
    int toCount = 0;
    if (emailTo.Length > 0)
    {
        foreach (string item in emailTo)
        {
            if (isValidEmail(item))
            { mailMsg.To.Add(new MailAddress(item)); toCount++; }
        }
        if (toCount < 1)
        { throw new Exception("EMAIL TO did not contain at least one valid email address"); }
    }
    else
    { throw new Exception("EMAIL TO must contain at least one address"); }

    string[] emailCC = cc.Split(";".ToCharArray());
    if (emailCC.Length > 0)
    {
        foreach (string itemCC in emailCC)
        {
            if (isValidEmail(itemCC))
                mailMsg.CC.Add(new MailAddress(itemCC));
        }
    }

    string[] emailBCC = bcc.Split(";".ToCharArray());
    if (emailBCC.Length > 0)
    {
        foreach (string itemBCC in emailBCC)
        {
            if (isValidEmail(itemBCC))
                mailMsg.Bcc.Add(new MailAddress(itemBCC));
        }
    }
    #endregion

    #region Email Attachments

    if (Attachments.Length > 0)
    {
        string[] fileAtt = Attachments.Split(";".ToCharArray());
        if (fileAtt.Length > 0)
        {
            foreach (string file in fileAtt)
            {
                mailMsg.Attachments.Add(new Attachment(file));
            }
        }
    }

    #endregion

    mailMsg.Subject = subj;
    mailMsg.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");

    if (!BodyText.Contains("<html><body>"))
    { BodyText = "<html><body>" + BodyText.Replace("\n", "<br />") + "</body></html>"; }
    else
    { BodyText = BodyText.Replace("\n", "<br />"); }

    AlternateView plainView =
        AlternateView.CreateAlternateViewFromString(Regex.Replace(BodyText, @"<(.|\n)*?>", string.Empty), null, "text/plain");
    AlternateView htmlView =
        AlternateView.CreateAlternateViewFromString(BodyText, null, "text/html");

    mailMsg.AlternateViews.Add(plainView);
    mailMsg.AlternateViews.Add(htmlView);

    try
    {
        SmtpClient client = new SmtpClient();
        client.Send(mailMsg);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

private static bool isValidEmail(string inputEmail)
{
    string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
    Regex re = new Regex(strRegex);
    return (re.IsMatch(inputEmail));
}
 
Thanks for the detailed replies :) I didn't expect answers so quickly and with such detail. However, I'm still a beginner with asp.net really, so still struggling with the basics.

1) Am I correct in thinking that if an existing site/project already has SMTP settings specified in the web.config in the <System.Web> tag, will it use that instead of this: [blue]smtpClient.Host = "POP3.website.com";[/blue]?

2) If the web.config already has <System.Web> tag is it possible to have a <System.Net> tag as well?

The reason why I am asking these questions is because I can send emails in my small testWebsite project with specifying the SMTPHost = POP3.website.com, but in an existing website I am trying to update I use the same line of code and in theory it should work because it is the same code as in the testWebsite! But the difference is with the site I am updating is that it has the <System.Web> tag in web.config and I can't see any other reason why it wouldn't work.

Once again, sorry for the newbie questions.
 
#2, yes

#1, im pretty sure no, the 1.1 way (system.web) i think of doing it was changed drastically. The 1.1 code was something like this... which was needed to provide the authentication mechanisms which mail servers started to implement to reduce unauthorized email.

Code:
            mailMessage.Fields("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpserverport")[/URL] = 25
            mailMessage.Fields("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusing")[/URL] = 2
            mailMessage.Fields("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")[/URL] = 1
            mailMessage.Fields("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendusername")[/URL] = ConfigurationSettings.AppSettings("smtpAccount")
            mailMessage.Fields("[URL unfurl="true"]http://schemas.microsoft.com/cdo/configuration/sendpassword")[/URL] = ConfigurationSettings.AppSettings("smtpAccountPW")

            System.Web.Mail.SmtpMail.SmtpServer = ConfigurationSettings.AppSettings("smtpServer")
            System.Web.Mail.SmtpMail.Send(mailMessage)
 
Thanks again adamroof, any ideas why the same code won't work in the website I am updating?
 
Change your code to catch the exception (if there is one that is preventing the updated site from sending) and let you know what it is, also if you have access to the server, it should be logged in the application event log that an unhandled exception ocurred. Start from there and post that error info.

if the code can access a label on your page, try this for now...

catch (Exception ex)
{ lblMessage.Text = ex.ToString(); }

It will usually spit out either a server communication error or authentication error or invalid email error.
 
system.net is new to asp.net 2.0, they can/must exist as separate nodes in the config file.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Thanks both of you for the information! I found out why the email didn't send, it was because I didn't specify an email address for the message.To.Add() so something quite simple I had missed.
 
Did you implement the exception handling still? You should. That will tell you what is missing right away.

And yes, i was assuming the System.Net tag was being used as a seperate node outside of the System.Web node.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top