Thesesixmust be selectedfrom a databasewith
multiple users inthedatabase that contains azip codeis included.
Howcan Imodifythe codeto read
alistof
recipientsfroma
datasource andsend an emailmessage toa
fewof therecipients
in theDataSourceUsing theSystem.Net.Mailclass
UserWebControl?
Here's thecode I
haveso far:
Public Class DistributionList
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim sentEmails As Integer
Public Function SendMail(ByVal mailMessage As System.Net.Mail.MailMessage) As Integer
AddHandler smtpClient.SendCompleted, AddressOf SmtpClient_OnCompleted
sentEmails = 0
Dim recipients As DataTable = GetRecipients()
For Each recipient As DataRow In recipients.Rows
mailMessage.To.Clear()
mailMessage.To.Add(New System.Net.Mail.MailAddress(recipient("Email"), (recipient("DisplayName"))))
SendMessage(mailMessage)
Next
Return sentEmails
End Function
Private Function GetRecipients() As DataTable
Dim table As New DataTable()
table.Columns.Add("DisplayName")
table.Columns.Add("Email")
Dim row As DataRow = table.NewRow()
row("DisplayName") = "John Doe"
row("Email") = "John@example.com"
table.Rows.Add(row)
Return table
End Function
Private Sub SendMessage(ByVal mailMessage As System.Net.Mail.MailMessage)
Dim userState As Object = mailMessage
Try
smtpClient.SendAsync(mailMessage, userState)
Catch failedRec As System.Net.Mail.SmtpFailedRecipientsException
'Choose to resend?
'Log failure of send here.
Catch smtpExc As System.Net.Mail.SmtpException
'Log failure of SMTP client here.
Catch ex As Exception
'Log exception here.
End Try
End Sub
Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
Dim mailMessage As System.Net.Mail.MailMessage = CType(e.UserState, System.Net.Mail.MailMessage)
If (e.Error Is Nothing) Then
sentEmails = sentEmails + 1
Else
'Write to your error log here that an email failed.
'Possibly include information from the mailMessage.
End If
End Sub
End Class
Hopefullysomeone
canhelpme on the way
to adjustthe code.
If you want to read a list of recipients from a data source, assuming you database is Sql database, then you can use SqlConnection, SqlCommand, SqlDataAdapter class to return DataTable.
For example:
connStr = ConfigurationManager.ConnectionStrings["WEBDBConnectionString"].ConnectionString;
string cmdText = string.Empty;
DataTable datatable = new DataTable();
using (SqlConnection sqlConn = new SqlConnection(connStr))
{
cmdText = "SELECT STU_NO,STU_NAME,STU_AGE FROM Student WHERE STU_NO='" + stuNo + "'";
SqlCommand sqlComm = new SqlCommand(cmdText);
sqlComm.Connection = sqlConn;
SqlDataAdapter dataAadapter = new SqlDataAdapter(sqlComm);
dataAadapter.Fill(datatable);
return datatable;
}
I'vetriedwith youranwsertoget thecorrectcodebutitdoes not work. TheemailsmustbesentwithaWebUserControl.ascxpage,the codeShould Beat theDistributieLijst.vb.
Thedistributionlist.vbcannothandlethe codeas givenby: ConfigurationManager.ConnectionStrings. Thecode give errors.(Iamworkingwith MicrosoftVisual WebDeveloper2010Express) I thinkthe codemodifiedtoDistributieLijst.vbShould Be. ThecodebelowShouldBe Replacedbyacode,Thatreadstheinformationfromthedatabase,sothats theemailgetsent toVarious /multiplerecipientsin the database.
This codesends anemail totherecipienti.e.John
Doe. The code Ineed is: Retrieve Name and Email Address andsorted byzipcodefrom
a database.
Private Function GetRecipients() As DataTable
Dim table As New DataTable()
table.Columns.Add("DisplayName")
table.Columns.Add("Email")
Dim row As DataRow = table.NewRow()
row("DisplayName") = "John Doe"
row("Email") = "John@example.com"
table.Rows.Add(row)
Return table
Have you add references to system.Configuration and use using statement (using System.Configuration) in your project? you don't need to place the database connection string in the web.config, you can directly use database connection string in your program,
something like below:
string connectionString="Data Source=(local);Initial Catalog=WEBDB;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(connectionString)
and you can use order by in your sql query statement to sort by zip code.
hello,
Below is a new custom VB language code, but this unfortunately does not send mail to recipients.
When debugging, the error in Email.ascx.vb:
The address parameter can not be an empty string.
Parameter name: address.
What needs to be changed?
Hoping for your help.
Regards,
TVW
DistributionList.vb
Imports System.Data.SqlClient
Public Class DistributionList
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim sentEmails As Integer
Private Property GetRecipients As New DataTable
Public Function SendMail(ByVal mailMessage As System.Net.Mail.MailMessage) As Integer
AddHandler smtpClient.SendCompleted, AddressOf SmtpClient_OnCompleted
sentEmails = 0
Dim recipients As DataTable = GetRecipients()
For Each recipient As DataRow In recipients.Rows
mailMessage.To.Clear()
mailMessage.To.Add(New System.Net.Mail.MailAddress(recipient("Email"), recipient("Name")))
SendMessage(mailMessage)
Next
Return sentEmails
End Function
Private Sub MakeMessage(ByVal mailMessage As System.Net.Mail.MailMessage)
Dim queryString As String = _
"SELECT Email, Name FROM recipients;"
Using connection As New SqlClient.SqlConnection(connectionString:="Data Source=|DataDirectory|\recipient.sdf")
Dim command As New SqlClient.SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlClient.SqlDataReader = command.ExecuteReader()
' Call Read before accessing data.
While reader.Read()
End While
' Call Close when done reading.
reader.Close()
End Using
End Sub
Private Sub SendMessage(ByVal mailMessage As System.Net.Mail.MailMessage)
Dim userState As Object = mailMessage
Try
smtpClient.SendAsync(mailMessage, userState)
Catch failedRec As System.Net.Mail.SmtpFailedRecipientsException
'Choose to resend?
'Log failure of send here.
Catch smtpExc As System.Net.Mail.SmtpException
'Log failure of SMTP client here.
Catch ex As Exception
'Log exception here.
End Try
End Sub
Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
Dim mailMessage As System.Net.Mail.MailMessage = CType(e.UserState, System.Net.Mail.MailMessage)
If (e.Error Is Nothing) Then
sentEmails = sentEmails + 1
Else
'Write to your error log here that an email failed.
'Possibly include information from the mailMessage.
End If
End Sub
End Class
Email.ascx.vb
Imports System.Net.Mail
Partial Class Email
Inherits System.Web.UI.UserControl
Private _recipient As String
Private Property recipient(p1 As String) As String
Get
Return _recipient
End Get
Set(value As String)
_recipient = value
End Set
End Property
Protected Sub btnSend_Click(ByVal sender As Object, e As System.EventArgs) Handles btnSend.Click
Dim distList As New HDI.Net.Mail.DistributionList
'Create instance of main mail message class
Dim mailMessage As New System.Net.Mail.MailMessage
mailMessage.Priority = Net.Mail.MailPriority.High
'Configure mail mesage
'Set the From address with user input
mailMessage.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim())
'Get From address in web.config
mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("fromEmailAddress"))
mailMessage.Subject = txtSubject.Text.Trim()
mailMessage.Body = txtBody.Text.Trim()
Dim sentMails As Integer = distList.SendMail(mailMessage)
'Add one to many attachments
'mailMessage.Attachments.Add(New System.Net.Mail.Attachment("c:\temp.txt")
'Create an instance of the SmtpClient class for sending the email
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
'Use a Try/Catch block to trap sending errors
'Especially useful when looping through multiple sends
Try
smtpClient.Send(mailMessage)
Catch smtpExc As System.Net.Mail.SmtpException
'Log error information on which email failed.
Catch ex As Exception
'Log general errors
End Try
End Sub
End Class
Superguppie.
Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
When all you've got is a Hammer, Every Problem looks like a Nail. Michael Swain.
Then I am guessing there was nothing in txtFrom. On emails the From field is mandatory.
Typically, this is taken care of using RequiredValidator. This will give the user a warning when the field is left empty, so it can be entered before actually doing anything.
Superguppie.
Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
When all you've got is a Hammer, Every Problem looks like a Nail. Michael Swain.
When the From field is left blank I get the above error. And I can see in Web Developer:
mailMessage = {MailMessage Mail System.Net..} mailMessage. From = Nothing txtFrom = {system.Web. TextBox Web controls, UI..} txtFrom .text = ""
When a valid email address is entered in the From field nothing happens in Web Developer and the Email is not sent to the recipients from database. Maybe the below code is not correct.
If you have any suggestions? Thanks in advance.
'Set the From address with user input
mailMessage.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim())
'Get From address in web.config
mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("FromEmailAddress"))
Superguppie.
Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
When all you've got is a Hammer, Every Problem looks like a Nail. Michael Swain.
tvw
Member
16 Points
9 Posts
How can I modify the code to read a list of recipients from a data source and send an email with ...
Jan 21, 2012 11:30 AM|LINK
Hello,
I have created a component for a website to send emails to users.
This video has really helped me with that:http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-a-reusable-component-for-sending-email-to-a-distribution-list
I want the users to send emails from the website at, say, 6 registered users in a database with the email address from a database are selected.
These six must be selected from a database with multiple users in the database that contains a zip code is included.
How can I modify the code to read a list of recipients from a data source and send an email message to a few of the recipients in the DataSource Using the System.Net.Mail class UserWebControl?
Here's the code I have so far:
Public Class DistributionList Dim smtpClient As New System.Net.Mail.SmtpClient() Dim sentEmails As Integer Public Function SendMail(ByVal mailMessage As System.Net.Mail.MailMessage) As Integer AddHandler smtpClient.SendCompleted, AddressOf SmtpClient_OnCompleted sentEmails = 0 Dim recipients As DataTable = GetRecipients() For Each recipient As DataRow In recipients.Rows mailMessage.To.Clear() mailMessage.To.Add(New System.Net.Mail.MailAddress(recipient("Email"), (recipient("DisplayName")))) SendMessage(mailMessage) Next Return sentEmails End Function Private Function GetRecipients() As DataTable Dim table As New DataTable() table.Columns.Add("DisplayName") table.Columns.Add("Email") Dim row As DataRow = table.NewRow() row("DisplayName") = "John Doe" row("Email") = "John@example.com" table.Rows.Add(row) Return table End Function Private Sub SendMessage(ByVal mailMessage As System.Net.Mail.MailMessage) Dim userState As Object = mailMessage Try smtpClient.SendAsync(mailMessage, userState) Catch failedRec As System.Net.Mail.SmtpFailedRecipientsException 'Choose to resend? 'Log failure of send here. Catch smtpExc As System.Net.Mail.SmtpException 'Log failure of SMTP client here. Catch ex As Exception 'Log exception here. End Try End Sub Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Dim mailMessage As System.Net.Mail.MailMessage = CType(e.UserState, System.Net.Mail.MailMessage) If (e.Error Is Nothing) Then sentEmails = sentEmails + 1 Else 'Write to your error log here that an email failed. 'Possibly include information from the mailMessage. End If End Sub End ClassHopefully someone can help me on the way to adjust the code.
Thanks in advance.
Peter pi - M...
Star
12871 Points
1786 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Jan 23, 2012 04:48 AM|LINK
Hi,
If you want to read a list of recipients from a data source, assuming you database is Sql database, then you can use SqlConnection, SqlCommand, SqlDataAdapter class to return DataTable.
For example:
connStr = ConfigurationManager.ConnectionStrings["WEBDBConnectionString"].ConnectionString; string cmdText = string.Empty; DataTable datatable = new DataTable(); using (SqlConnection sqlConn = new SqlConnection(connStr)) { cmdText = "SELECT STU_NO,STU_NAME,STU_AGE FROM Student WHERE STU_NO='" + stuNo + "'"; SqlCommand sqlComm = new SqlCommand(cmdText); sqlComm.Connection = sqlConn; SqlDataAdapter dataAadapter = new SqlDataAdapter(sqlComm); dataAadapter.Fill(datatable); return datatable; }Here is a similar post related to send email to multiple recipients.
http://forums.asp.net/t/1135988.aspx
If I misunderstood your meaning, please follow up here.
Regards,
Peter
If you have any feedback about my replies, please contact msdnmg@microsoft.com
Microsoft One Code Framework
tvw
Member
16 Points
9 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Jan 23, 2012 12:32 PM|LINK
This code sends an email to the recipient i.e. John Doe.
The code I need is:
Retrieve Name and Email Address and sorted by zip code from a database.
Private Function GetRecipients() As DataTable Dim table As New DataTable() table.Columns.Add("DisplayName") table.Columns.Add("Email") Dim row As DataRow = table.NewRow() row("DisplayName") = "John Doe" row("Email") = "John@example.com" table.Rows.Add(row) Return tablePeter pi - M...
Star
12871 Points
1786 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Jan 30, 2012 07:49 AM|LINK
Hi,
Have you add references to system.Configuration and use using statement (using System.Configuration) in your project? you don't need to place the database connection string in the web.config, you can directly use database connection string in your program, something like below:
and you can use order by in your sql query statement to sort by zip code.
Hope this helps
Regards,
Peter
If you have any feedback about my replies, please contact msdnmg@microsoft.com
Microsoft One Code Framework
tvw
Member
16 Points
9 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Feb 05, 2012 08:51 AM|LINK
hello,
Below is a new custom VB language code, but this unfortunately does not send mail to recipients.
When debugging, the error in Email.ascx.vb:
The address parameter can not be an empty string.
Parameter name: address.
What needs to be changed?
Hoping for your help.
Regards,
TVW
DistributionList.vb
Imports System.Data.SqlClient Public Class DistributionList Dim smtpClient As New System.Net.Mail.SmtpClient() Dim sentEmails As Integer Private Property GetRecipients As New DataTable Public Function SendMail(ByVal mailMessage As System.Net.Mail.MailMessage) As Integer AddHandler smtpClient.SendCompleted, AddressOf SmtpClient_OnCompleted sentEmails = 0 Dim recipients As DataTable = GetRecipients() For Each recipient As DataRow In recipients.Rows mailMessage.To.Clear() mailMessage.To.Add(New System.Net.Mail.MailAddress(recipient("Email"), recipient("Name"))) SendMessage(mailMessage) Next Return sentEmails End Function Private Sub MakeMessage(ByVal mailMessage As System.Net.Mail.MailMessage) Dim queryString As String = _ "SELECT Email, Name FROM recipients;" Using connection As New SqlClient.SqlConnection(connectionString:="Data Source=|DataDirectory|\recipient.sdf") Dim command As New SqlClient.SqlCommand(queryString, connection) connection.Open() Dim reader As SqlClient.SqlDataReader = command.ExecuteReader() ' Call Read before accessing data. While reader.Read() End While ' Call Close when done reading. reader.Close() End Using End Sub Private Sub SendMessage(ByVal mailMessage As System.Net.Mail.MailMessage) Dim userState As Object = mailMessage Try smtpClient.SendAsync(mailMessage, userState) Catch failedRec As System.Net.Mail.SmtpFailedRecipientsException 'Choose to resend? 'Log failure of send here. Catch smtpExc As System.Net.Mail.SmtpException 'Log failure of SMTP client here. Catch ex As Exception 'Log exception here. End Try End Sub Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Dim mailMessage As System.Net.Mail.MailMessage = CType(e.UserState, System.Net.Mail.MailMessage) If (e.Error Is Nothing) Then sentEmails = sentEmails + 1 Else 'Write to your error log here that an email failed. 'Possibly include information from the mailMessage. End If End Sub End ClassEmail.ascx.vbImports System.Net.Mail Partial Class Email Inherits System.Web.UI.UserControl Private _recipient As String Private Property recipient(p1 As String) As String Get Return _recipient End Get Set(value As String) _recipient = value End Set End Property Protected Sub btnSend_Click(ByVal sender As Object, e As System.EventArgs) Handles btnSend.Click Dim distList As New HDI.Net.Mail.DistributionList 'Create instance of main mail message class Dim mailMessage As New System.Net.Mail.MailMessage mailMessage.Priority = Net.Mail.MailPriority.High 'Configure mail mesage 'Set the From address with user input mailMessage.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim()) 'Get From address in web.config mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("fromEmailAddress")) mailMessage.Subject = txtSubject.Text.Trim() mailMessage.Body = txtBody.Text.Trim() Dim sentMails As Integer = distList.SendMail(mailMessage) 'Add one to many attachments 'mailMessage.Attachments.Add(New System.Net.Mail.Attachment("c:\temp.txt") 'Create an instance of the SmtpClient class for sending the email Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient() 'Use a Try/Catch block to trap sending errors 'Especially useful when looping through multiple sends Try smtpClient.Send(mailMessage) Catch smtpExc As System.Net.Mail.SmtpException 'Log error information on which email failed. Catch ex As Exception 'Log general errors End Try End Sub End Classsuperguppie
All-Star
48225 Points
8679 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Feb 10, 2012 03:15 PM|LINK
At what line does it say that?
Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
When all you've got is a Hammer, Every Problem looks like a Nail. Michael Swain.
tvw
Member
16 Points
9 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Feb 11, 2012 09:06 AM|LINK
In: Email.ascx.vb
mailMessage.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim())
superguppie
All-Star
48225 Points
8679 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Feb 14, 2012 02:58 PM|LINK
Then I am guessing there was nothing in txtFrom. On emails the From field is mandatory.
Typically, this is taken care of using RequiredValidator. This will give the user a warning when the field is left empty, so it can be entered before actually doing anything.
Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
When all you've got is a Hammer, Every Problem looks like a Nail. Michael Swain.
tvw
Member
16 Points
9 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Feb 15, 2012 12:44 PM|LINK
Thank you for your response,
When the From field is left blank I get the above error. And I can see in Web Developer:
mailMessage = {MailMessage Mail System.Net..} mailMessage. From = Nothing txtFrom = {system.Web. TextBox Web controls, UI..} txtFrom .text = ""
When a valid email address is entered in the From field nothing happens in Web Developer and the Email is not sent to the recipients from database. Maybe the below code is not correct.
If you have any suggestions? Thanks in advance.
'Set the From address with user input mailMessage.From = New System.Net.Mail.MailAddress(txtFrom.Text.Trim()) 'Get From address in web.config mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("FromEmailAddress"))superguppie
All-Star
48225 Points
8679 Posts
Re: How can I modify the code to read a list of recipients from a data source and send an email w...
Feb 17, 2012 03:10 PM|LINK
The smtpClient.Send does happen?
Have you been able to send email this way before?
Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
When all you've got is a Hammer, Every Problem looks like a Nail. Michael Swain.