Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET and Web » Sending Emails using web.config file's credential

Sending Emails using web.config file's credential

This article will explain you, how to send emails with attachment in ASP.Net using VB Language and to use the credentials from web.config file.

Author Rank :
Page Views : 2159
Downloads : 44
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Sending Email ASP.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

It is very easy to send emails from ASP.Net using any language like VB or C#, but there is no any article which explains that how to use credentials from web.config file. In general, to send email we also use to type the sender's email ID that is FROM address. It is very bored work to do the same thing always. There should be any other way to define the FROM email address once, like in web.config file and use it entirely in website. Let's take a look.

Perquisite

To understand this project, you should have general email sending technique. Because, in this article, basics are not covered.

Credentials

To call the credentials from web.config file we use to write

Dim mysmtp As New System.Net.Mail.SmtpClient()

In Default.aspx.vb page. And in web.config file we use to write the following

<system.net>
    <
mailSettings>
      <
smtp>
        <
network
          host="smtp.domainname.com"
          userName="username@domainname.com"
          password="xxxxxxxxx"
          port="25"/>
      </smtp>
    </
mailSettings>
  </system.net>

Above codes should be placed within <configuration> tag.

FROM address in web.config file

In web.config file we use to write the following

<appSettings>
    <
add key="mydefaultFROM" value="username@domainname.com"/>
</appSettings>

In above code value should be same as username in very above coding, key is just a calling name used inside Default.aspx.vb page as follows

mailmsg.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim())

mailmsg.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationSettings.AppSettings("mydefaultFROM"))


In above coding, use any one, like, if you want to use textbox on form to write FROM email address then use 'red' colored coding but want to use web.config file use below the 'red' colored coding.

Default.aspx Coding

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<
html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Sending Email with Attachement in ASP.Net using VB Language</title>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <strong><span style="text-decoration: underline; font-size: 14pt; color: #3300ff;">Sending Email with Attachement in ASP.Net using
            VB Language</span></strong><br />
        <br />
        <span style="font-size: 10pt; font-family: Verdana"><strong>Note:</strong> Please note
            that, in this project I have used to way to represent the FROM address. First way
            is to write the from address at run time and second one is to include the from address
            in web.config file and the same mention in Default.aspx.vb page, it will work perfectly
            with giving FROM address at runtime. From address can be any mail id. </span>
        <br />
        <br />
        <table style="width: 465px; height: 61px" bgcolor="#dcdcdc">
            <tr>
                <td style="width: 66px">
                </td>
                <td style="width: 76px">
                    <br />
                    <asp:Label ID="lblInfo" runat="server" Width="212px" Font-Names="Berlin Sans FB Demi" ForeColor="Red"></asp:Label><br />
                </td>
                <td style="width: 53px">
                </td>
            </tr>
            <tr>
                <td style="width: 66px">
                    From:</td>
                <td style="width: 76px">
                    <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox></td>
                <td style="width: 53px">
                </td>
            </tr>
            <tr>
                <td style="width: 66px">
                    To:</td>
                <td style="width: 76px">
                    <asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td>
                <td style="width: 53px">
                </td>
            </tr>
            <tr>
                <td style="width: 66px">
                    Subject:</td>
                <td style="width: 76px">
                    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
                <td style="width: 53px">
                </td>
            </tr>
            <tr>
                <td style="width: 66px">
                    Message:</td>
                <td style="width: 76px">
                    <asp:TextBox ID="txtMessage" runat="server" Height="60px" TextMode="MultiLine" Width="199px"></asp:TextBox></td>
                <td style="width: 53px">
                </td>
            </tr>
            <tr>
                <td style="width: 66px">
                    Attachement:</td>
                <td style="width: 76px">
                    <asp:FileUpload ID="FileUpload1" runat="server" /></td>
                <td style="width: 53px">
                    </td>
            </tr>
            <tr>
                <td style="width: 66px">
                </td>
                <td style="width: 76px">
                </td>
                <td style="width: 53px">
                </td>
            </tr>
            <tr>
                <td style="width: 66px">
                </td>
                <td style="width: 76px">
                    <asp:Button ID="send" runat="server" Text="Send" Width="78px" /></td>
                <td style="width: 53px">
                </td>
            </tr>
        </table>
   
    </div>
    </form>
</body>
</
html>

Default.aspx.vb Coding

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub send_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles send.Click

        If txtTo.Text = "" Or txtMessage.Text = "" Then

            lblInfo.Text = "Complete your email."

        Else

            '******************************************************************
            'declaring the mailing class
            '******************************************************************
            Dim mailmsg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
 
            '******************************************************************
            'declaring the FROM email address we can also define the standard
            '******************************************************************

            'Normal FROM email address using (only one can run at once)
            '------------------------------------------------------------------
            mailmsg.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim())

            'FROM address in web.config file and then we can call that as
            '-----------------------------------------------------------------
            'mailmsg.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationSettings.AppSettings("mydefaultFROM"))

            '*****************************************************************
            'declaring the TO email address, there can be multiple email addresses
            '*****************************************************************
            mailmsg.To.Add(New System.Net.Mail.MailAddress(txtTo.Text.Trim()))
            'mailmsg.CC.Add
            'mailmsg.BCC.Add
            'mailmsg.ReplyTo.Add

            '*****************************************************************
            'declaring the Subject of email
            '*****************************************************************
            mailmsg.Subject = txtSubject.Text.Trim()

            '*****************************************************************
            'declaring the Mail Body of email, here we can change to send
            'the database data or form result as we can say
            '*****************************************************************
            mailmsg.Body = txtMessage.Text.Trim()

            '*****************************************************************
            'sending attachements
            '*****************************************************************
            'mailmsg.Attachments.Add(New System.Net.Mail.Attachment("C:\abhi.txt"))
            If FileUpload1.HasFile = True Then
                Dim fu As FileUpload = FileUpload1
                Dim ct As String = fu.PostedFile.ContentType

                'Get file name from fully qualified file name
                Dim fn As String = fu.PostedFile.FileName
                Dim c As Integer = fn.LastIndexOf("\")
                fn = fn.Substring(c + 1)

                mailmsg.Attachments.Add(New System.Net.Mail.Attachment(fu.PostedFile.InputStream, fn, ct))
            End If

            '*****************************************************************
            'setting up the smpt configuration
            'Dim mysmtp As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
            '*****************************************************************
            Dim mysmtp As New System.Net.Mail.SmtpClient()

            '****************************************************************
            'final step to send email
            '****************************************************************
            Try

                mysmtp.Send(mailmsg)

            Catch mysmtpexp As System.Net.Mail.SmtpException
                'log error details will be here
            Catch ex As Exception
                'log error details will be here
            End Try

            '****************************************************************
            'display the message for conformation
            '****************************************************************
            lblInfo.Text = "Email Sent"

        End If

    End Sub
End Class

Web.config Coding

<?xml version="1.0"?>
<configuration>
  <
appSettings>
   
    <
add key="mydefaultFROM" value="username@domainname.com"/>
  </
appSettings>
      <
connectionStrings/>
      <
system.web>
           
            <
compilation debug="true"/>

            <authentication mode="Windows"/>

      </system.web>
  <
system.net>
    <
mailSettings>
      <
smtp>
        <
network
          host="smtp.domainname.com"
          userName="username@domainname.com"
          password="xxxxxxxxx"
          port="25"/>
      </smtp>
    </
mailSettings>
  </
system.net>
</
configuration>

figure.gif

HAVE A HAPPY CODING!

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Abhimanyu Kumar Vatsa
http://www.itorian.com/about/
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.