Solved

web.config mutliple smtp accounts

Posted on 2012-03-14
9
1,137 Views
Last Modified: 2012-03-21
I have a web application that is accessable via 2 different domains and I need to send out emails using 2 different smtp accounts because of the 2 domains. This is to avoid emails being marked as unsafe, phishing or spam due to being sent from an address that doesn't match the mailserver.

Is there a way to do this even though the web.config SMTP settings area will only allow 1 account. IF so, how?

Can I send the emails some other way rather than using the settings stored in web.config?
IF so, how?

THanks
Simon
0
Comment
Question by:swgdesign
  • 4
  • 4
9 Comments
 
LVL 16

Expert Comment

by:Rose Babu
ID: 37719687
0
 

Author Comment

by:swgdesign
ID: 37719828
I did see this code but I don't understand the accepted answer or how to implement it, it seems bitty?

I understand that you can declare a new declaration and name it and then setup a new section using this declaration...

<configSections>
  <section name="smtp_3" type="System.Net.Configuration.SmtpSection"/>
</configSections>
<mailSettings>
    <smtp_1 deliveryMethod="Network" from="mail1@temp.uri">
      <network host="..." defaultCredentials="false"/>
    </smtp_1>
</mailsettings

Open in new window


BUT what I don't understand is this part and how it is used in sending an email

return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_2");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_3");

Open in new window


At the moment I use a function in a class that accepts the following parameters;

 Public Shared Sub SendMailMessage(ByVal Sender As String, ByVal Recipient As String, ByVal BCC As String, ByVal CC As String, ByVal Subject As String, ByVal Body As String)

Open in new window

0
 
LVL 15

Expert Comment

by:jorge_toriz
ID: 37722844
I would store the values inside appSettings node
0
 
LVL 16

Expert Comment

by:Rose Babu
ID: 37723756
http://stackoverflow.com/questions/4363038/setting-multiple-smtp-settings-in-web-config
Yes, That solution is confusing to implement.

instead of storing SMTP details in web.config file, do you agree to store SMTP details in a XML file and read the data dynamically in your mailing process?

This will allow you to store multiple SMTP details and retrieve while sending a mail (using dynamic SMTP details). if so i can provide some more details with sample code.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:swgdesign
ID: 37723829
I am open to either using appSettings or an XML file.

Can either fo you give me an example of what needs to be setup coded to implement such a solution?

POints increased :)
0
 
LVL 16

Accepted Solution

by:
Rose Babu earned 500 total points
ID: 37724043
i have modified your SendMailMessage function with one new parameter as _SMTPNAME. it will be used to pass the smtp name which will be used to find the smtp details.

remove any of the MailSettings mentioned in web.config.

GetSMTPDet function will return the smtp details for the specified smtp name.

Sample XML file with multiple smtp details. (if you wish, you can encrypt the smtp details and store in xml. And then decrypt and set in smtp client object)
<?xml version="1.0" encoding="UTF-8"?>
<smtp_servers>
  <smtp name="smtp1">
    <host>smtp.domain1.com</host>
    <port>25</port>
    <username>testUser1</username>
    <password>testPassword1</password>
  </smtp>
  <smtp name="smtp2">
    <host>smtp.domain2.com</host>
    <port>25</port>
    <username>testUser2</username>
    <password>testPassword2</password>
  </smtp>
  <smtp name="smtp3">
    <host>smtp.domain3.com</host>
    <port>25</port>
    <username>testUser3</username>
    <password>testPassword3</password>
  </smtp>
</smtp_servers>

Open in new window

To protect the xml file(__SecureSmtpConfig.xml used in my sample), you can add the below code in your web config.
<location path="__SecureSmtpConfig.xml">
<system.web>
  <authorization>
	<deny users="*" />        
  </authorization>
</system.web>
</location>

Open in new window

Sample code to send email using dynamic smtp details
Imports System.Xml
Imports System.Net.Mail

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	If Not Page.IsPostBack Then

		' Test Mail Function Call
		
		SendMailMessage("smtp1", "test1@test1.com", "test2@test1.com", "", "", "Subject", "MsgBody")
		'SendMailMessage("smtp2", "test1@test1.com", "test2@test1.com", "", "", "Subject", "MsgBody")
		'SendMailMessage("smtp3", "test1@test1.com", "test3@test1.com", "", "", "Subject", "MsgBody")

	End If

End Sub

Public Sub SendMailMessage(ByVal _SMTPNAME As String, ByVal Sender As String, ByVal Recipient As String, ByVal BCC As String, ByVal CC As String, ByVal Subject As String, ByVal Body As String)

	' Sample email process. SMTP client details are retrieved dynamically
	
	Dim message As New MailMessage(Sender, Recipient)
	message.Subject = "Using the new SMTP client."
	message.Body = "Using this new feature, you can send an e-mail message from an application very easily."

	Dim SmtpDet As New _SMTP_Det
	SmtpDet = GetSMTPDet(_SMTPNAME)

	' Set Host, Port and Credentials
	Dim client As New SmtpClient()
	client.Host = SmtpDet.HostName
	client.Port = SmtpDet.Port
	client.Credentials = New System.Net.NetworkCredential(SmtpDet.UserName, SmtpDet.Password)

	Try
		client.Send(message)
	Catch ex As Exception
		Dim exMsg = ex.Message
		
	End Try

End Sub

Public Class _SMTP_Det
	Public HostName As String = ""
	Public Port As String = ""
	Public UserName As String = ""
	Public Password As String = ""
End Class

Public Function GetSMTPDet(ByVal _SMTPNAME As String) As _SMTP_Det

	Dim retSmtp As New _SMTP_Det

	Dim xmlDoc As New XmlDocument
	xmlDoc.Load(Server.MapPath("__SecureSmtpConfig.xml"))

	Dim root As XmlElement = xmlDoc.DocumentElement
	Dim smtpName As String = ""

	For Each elem As XmlElement In root.GetElementsByTagName("smtp")

		smtpName = elem.GetAttribute("name")

		If smtpName = _SMTPNAME Then

			retSmtp.HostName = elem.GetElementsByTagName("host").Item(0).InnerText
			retSmtp.Port = elem.GetElementsByTagName("port").Item(0).InnerText
			retSmtp.UserName = elem.GetElementsByTagName("username").Item(0).InnerText
			retSmtp.Password = elem.GetElementsByTagName("password").Item(0).InnerText

			Exit For
		End If
	Next

	Return retSmtp

End Function

Open in new window

Try this code. Hope this will work for you.
0
 

Author Comment

by:swgdesign
ID: 37724336
That look complete and exactly what I could do with. Give me a day or so and I'll get back to you if it works :)
0
 

Author Comment

by:swgdesign
ID: 37728659
Quick question...

At the moment 'SendMailMessage' is within a class called EmailHelper in a file called email.vb. I call SendEmailMessage in my code by using EmailHelper.SendMailMessage().

Can I just insert your code within my EmailHelper class?

Imports System.Web
Imports System.Xml
Imports System.Net.Mail


Public Class EmailHelper

    Public Shared Sub SendMailMessage(ByVal Sender As String, ByVal Recipient As String, ByVal BCC As String, ByVal CC As String, ByVal Subject As String, ByVal Body As String)
        Dim mMailMessage As New MailMessage()
        mMailMessage.From = New MailAddress(Sender)
        mMailMessage.To.Add(New MailAddress(Recipient))

        If Not String.IsNullOrEmpty(BCC) Then
            mMailMessage.Bcc.Add(New MailAddress(BCC))
        End If

        If Not String.IsNullOrEmpty(CC) Then
            mMailMessage.CC.Add(New MailAddress(CC))
        End If

        mMailMessage.Subject = Subject
        mMailMessage.Body = Body
        mMailMessage.IsBodyHtml = True
        mMailMessage.Priority = MailPriority.Normal
        Dim mSmtpClient As New SmtpClient()
        mSmtpClient.Send(mMailMessage)
    End Sub
End Class

Open in new window

0
 
LVL 16

Expert Comment

by:Rose Babu
ID: 37728830
Yes,

you can add my sample in a class file (EmailHelper.vb) and use it.
Dim emailObj As New EmailHelper

emailObj.SendMailMessage("smtp1", "test1@test1.com", "test11@test1.com", "", "", "Subject 1", "MsgBody 1")
'emailObj.SendMailMessage("smtp2", "test2@test1.com", "test22@test1.com", "", "", "Subject 2", "MsgBody 2")
'emailObj.SendMailMessage("smtp3", "test3@test1.com", "test33@test1.com", "", "", "Subject 3", "MsgBody 3")

Open in new window

Below is the EmailHelper class as you need and I HAVE UPDATED ONE LINE IN THE CODE.
' EmailHelper.vb
' Updated by Rose :-
'
' To read the __SecureSmtpConfig.xml file, i used Server.MapPath("__SecureSmtpConfig.xml")
' but inside the class we need to do call the file by the below line of code
' System.Web.HttpContext.Current.Server.MapPath("__SecureSmtpConfig.xml")
'
Imports System.Xml
Imports System.Net.Mail

Public Class EmailHelper

#Region "Dynamic SMTP"

    Public Sub SendMailMessage(ByVal _SMTPNAME As String, ByVal Sender As String, ByVal Recipient As String, ByVal BCC As String, ByVal CC As String, ByVal Subject As String, ByVal Body As String)

        Dim message As New MailMessage(Sender, Recipient)
        message.Subject = "Using the new SMTP client." & Subject
        message.Body = "Using this new feature, you can send an e-mail message from an application very easily." & Environment.NewLine & Body

        Dim SmtpDet As New _SMTP_Det
        SmtpDet = GetSMTPDet(_SMTPNAME)

        ' host, port, and credentials.
        Dim client As New SmtpClient()
        client.Host = SmtpDet.HostName
        client.Port = SmtpDet.Port
        client.Credentials = New System.Net.NetworkCredential(SmtpDet.UserName, SmtpDet.Password)

        Try
            client.Send(message)
        Catch ex As Exception

            Dim exMsg = ex.Message
            ' Or
            'Throw ex

        End Try

    End Sub

    Public Class _SMTP_Det
        Public HostName As String = ""
        Public Port As String = ""
        Public UserName As String = ""
        Public Password As String = ""
    End Class

    Public Function GetSMTPDet(ByVal _SMTPNAME As String) As _SMTP_Det

        Dim retSmtp As New _SMTP_Det

        Dim xmlDoc As New XmlDocument
        'xmlDoc.Load(Server.MapPath("__SecureSmtpConfig.xml")) ' I modified this line
        xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("__SecureSmtpConfig.xml"))

        Dim root As XmlElement = xmlDoc.DocumentElement
        Dim smtpName As String = ""

        For Each elem As XmlElement In root.GetElementsByTagName("smtp")

            smtpName = elem.GetAttribute("name")

            If smtpName = _SMTPNAME Then

                retSmtp.HostName = elem.GetElementsByTagName("host").Item(0).InnerText
                retSmtp.Port = elem.GetElementsByTagName("port").Item(0).InnerText
                retSmtp.UserName = elem.GetElementsByTagName("username").Item(0).InnerText
                retSmtp.Password = elem.GetElementsByTagName("password").Item(0).InnerText

                Exit For

            End If
        Next

        Return retSmtp

    End Function

#End Region
End Class

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

746 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now