Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Send an email from ASP.NET Page

Posted on 2012-03-22
8
Medium Priority
?
333 Views
Last Modified: 2012-04-10
Hi,

I want to send email thru a website application I am developing. I need the code for this, and would like to know how to place SMTP host name, email-id, and password in the code from where the mail must go.

Thanks.
0
Comment
Question by:sanjay-gandhi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 14

Expert Comment

by:binaryevo
ID: 37752652
internal class Mailer
    {
        private const int Timeout = 180000;

        private readonly string _host;
        private readonly int _port;
        private readonly string _user;
        private readonly string _pass;
        private readonly bool _ssl;

        public string Sender { get; set; }
        public string Recipient { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentFile { get; set; }

        public Mailer()
        {
            _host = ConfigurationManager.AppSettings["MailServer"];
            _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            _user = ConfigurationManager.AppSettings["MailAuthUser"];
            _pass = ConfigurationManager.AppSettings["MailAuthPass"];
            _ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
        }

        public void Send()
        {
            // We do not catch the error here... let it pass direct to the caller
            Attachment att = null;
            var message = new MailMessage(Sender, Recipient, Subject, Body) {IsBodyHtml = true};
            var smtp = new SmtpClient(_host, _port);
            
            if (!String.IsNullOrEmpty(AttachmentFile))
            {
                if (File.Exists(AttachmentFile))
                {
                    att = new Attachment(AttachmentFile);
                    message.Attachments.Add(att);
                }
            }

            if (_user.Length > 0 && _pass.Length > 0)
            {
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new NetworkCredential(_user, _pass);
                smtp.EnableSsl = _ssl;
            }

            smtp.Timeout = Timeout;
            smtp.Send(message);

            if (att != null)
                att.Dispose();
            message.Dispose();
            smtp.Dispose();
        }
    }

Open in new window

0
 
LVL 9

Expert Comment

by:gery128
ID: 37753050
Apart from the solution suggested by binaryevo, I would like to add one more thing.

Encrypt your <appSettings> section of Web.Config for better security.
0
 
LVL 14

Expert Comment

by:binaryevo
ID: 37753102
Agreed with gery128, security is of utmost importance.
0
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 

Author Comment

by:sanjay-gandhi
ID: 37753628
Your code must be fine, but its giving me some errors. Let me tell you I am quite new to ASP.NET, which is why also I need help. So please tell me why am I getting these errors, attached.
Errors.png
0
 
LVL 14

Expert Comment

by:binaryevo
ID: 37753762
1)  Your button, BtCheckMail doesnt have an event associated with the button click.  Open up
design view of your webform and double click the button to resolve this.  It will take you to codebehind where the event will be created.

2)  Add the following to the top of the class in the using statements section:

using System.Net.Mail;

Open in new window

0
 

Author Comment

by:sanjay-gandhi
ID: 37757162
Sorry but I still find the errors appearing. I am attaching the code and the errors, plus I have also opened the event on Button, but if I try to use Send over there, it does not accept. Yes I've yet not added the SMTP link, which I can only try once my code is error free.

Thanks.
SendMail.zip
0
 
LVL 9

Accepted Solution

by:
gery128 earned 2000 total points
ID: 37764554
Hi Sanjay,
Can you try this code for "Check Mail.aspx.cs"?
What you need to do is, replace below code with your "Check Mail.aspx.cs" file code and then compile.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.IO;
using System.Net;

public partial class Check_Mail : System.Web.UI.Page
{
    internal class Mailer
    {
        private const int Timeout = 180000;

        private readonly string _host;
        private readonly int _port;
        private readonly string _user;
        private readonly string _pass;
        private readonly bool _ssl;

        public string Sender { get; set; }
        public string Recipient { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string AttachmentFile { get; set; }

        public Mailer()
        {
            _host = ConfigurationManager.AppSettings["MailServer"];
            _port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            _user = ConfigurationManager.AppSettings["MailAuthUser"];
            _pass = ConfigurationManager.AppSettings["MailAuthPass"];
            _ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
        }

        public void Send()
        {
            // We do not catch the error here... let it pass direct to the caller
            Attachment att = null;
            var message = new MailMessage(Sender, Recipient, Subject, Body) { IsBodyHtml = true };
            var smtp = new SmtpClient(_host, _port);

            if (!String.IsNullOrEmpty(AttachmentFile))
            {
                if (File.Exists(AttachmentFile))
                {
                    att = new Attachment(AttachmentFile);
                    message.Attachments.Add(att);
                }
            }

            if (_user.Length > 0 && _pass.Length > 0)
            {
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new NetworkCredential(_user, _pass);
                smtp.EnableSsl = _ssl;
            }

            smtp.Timeout = Timeout;
            smtp.Send(message);

            if (att != null)
                att.Dispose();
            message.Dispose();
            smtp = null;
        }
    }
    protected void BtCheckMail_Click(object sender, EventArgs e)
    {
        /*-- This is my BtCheckMail event, what code comes here --*/
    }
}

Open in new window

0
 

Author Closing Comment

by:sanjay-gandhi
ID: 37828831
Thanks, sorry for delayed response. Got busy travelling and in an assignment.
My programmer could make really good use of it. Works, thanks.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question