How to put Dataset query results into the body of an email - vb.net

I'm trying to make a program that emails the results of a query (in a dataset) to a user... My code is:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Paid_Out_TbTableAdapter.Fill(Me.dataset.Paid_Out_Tb)
Me.ReportViewer1.RefreshReport()
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New _
Net.NetworkCredential("Bob", "password")
SmtpServer.Port = 25
SmtpServer.Host = "server"
mail = New MailMessage()
mail.From = New MailAddress("email#email.com")
mail.To.Add("Email#email.com")
mail.Subject = "Test Mail"
mail.Body = (Me.DataSet.Paid_Out_Tb.ToString)
SmtpServer.Send(mail)
MsgBox("mail send")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Everything works except sending the email body... How can i get the results to email as the body?

You can use Linq and VB's new inline xml literals capability to generate the html. Try this:
Dim payOuts = _
<html>
<body>
<table>
<tr><th>My First Column Header</th><th>My Second Column Header</th></tr>
<%= From paidOut In Me.DataDeliveryServiceDataSet.Paid_Out_Tb.AsEnumerable _
Select <tr>
<td><%= paidOut.MyFirstColum %></td>
<td><%= paidOut.MySecondColum %></td>
</tr> %>
</table>
</body>
</html>
mail.IsBodyHtml = True
mail.Body = payouts.ToString
Be sure to include a reference to System.Data.DataSetExtensions.dll in your project if it isn't already there. You'll also need Imports System.Linq on your class. See the Using LINQ and XML Literals to transform a DataTable into a HTML table blog posting by Éric Moreau for a good explanation.

You will need to cycle through the rows of the dataset and extract the data you wish to email. You can format it using HTML by adding the following statement:
mail.IsBodyHtml = True

Related

Set radio button list from vb code behind

I have a radio button list. When the page is loaded I have some scripts and other things that run to determine if an ID has passed or failed a test. So what I am trying to actually do is when that page loads set my radio button to fail after the script runs
Here is the list:
<asp:radiobuttonlist id="rblInspectionStatus" CssClass="descbold" runat="server" repeatColumns="2" repeatDirection="Horizontal">
<asp:listitem Value="Pass">Pass</asp:listitem>
<asp:listitem Value="Fail">Fail</asp:listitem>
</asp:radiobuttonlist>
What I have tried is:
rblInspectionStatus.Items.FindByValue("Fail").Selected = True
rblInspectionStatus.Items.FindByText("Fail").Selected = True
rblInspectionStatus.SelectedIndex |SelectedItem | SelectedValue
I don't know what you are trying to do in that Sub or as User Tony Hinkle and User NoAlias are trying to say is correct but this is my assumption:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn.Open() 'Opens the connection
cmd = New SqlCommand("SELECT PF FROM TABLE WHERE ID = '" & Session("ID") & "'", cn)
drr = cmd.ExecuteReader
If drr.Read Then
rblInspectionStatus.ClearSelection()
rblInspectionStatus.Items.FindByValue(drr.Items("PF")).Selected = True
'FIELD PF data either Pass or Fail
ElseIf Not drr.Read Then
rblInspectionStatus.ClearSelection()
rblInspectionStatus.SelectedIndex = -1
End If
cn.Close() 'Close the connection
End Sub

Writing multiple SQL server tables as separate nodes to XML Document

I have multiple SQL server tables from which I want to pull data and write to XML. I want my XML to be formed like this:
<Data>
<Query1Table>
<Table>
<Column1>Data</Column1>
<Column2>Data</Column2>
...
</Table>
</Query1Table>
<Query2Table>
<Table>
<Column1>Data</Column1>
<Column2>Data</Column2>
...
</Table>
</Query2Table>
</Data>
I'm using datasets to write the xml, but the code I'm working with doesn't append the data, it overwrites:
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim directory As String
Dim ds As New DataSet
Dim sql As String
connection = New SqlConnection(connetionString)
sql = "select * from scheduledata"
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
ds.DataSetName = "Schedule"
ds.WriteXml(directory)
ds.Clear()
sql = "select * from costdata"
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
ds.WriteXml(directory)
I have tried adding it all to the same data set by calling the SQL queries at once, but that doesn't help to separate them in the XML -- it groups them in the same node.
I'm open to a different method if anyone has a good suggestion.
You've defined directory as a string, so ds.WriteXml will (create and) write to a file by that name.
Use a FileStream or XmlTextWriter instead.
The way that I write to .xml files (which works) is as follows
Private Sub AuthenticationContinuebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthenticationContinuebtn.Click
On Error GoTo PasswordHandler
GlobalVariables.Username = Usernametxtbx.Text
GlobalVariables.Password = Passwordtxtbx.Text
GetUsernamePassword()
Close()
Exit Sub
PasswordHandler:
MsgBox("Incorrect password or username.")
End Sub
Private Sub UserAuthenticationWindow_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim FileName4 As String = "C:\Forte\UsernamePassword.xml"
Dim FileRead4 As XmlTextReader = New XmlTextReader("C:\Forte\UsernamePassword.xml")
'If statement to see if file exists.
If System.IO.File.Exists(FileName4) = True Then
Do While (FileRead4.Read)
Select Case FileRead4.NodeType
Case XmlNodeType.Text, XmlNodeType.Element
If FileRead4.Name = "Username" Then
FileRead4.Read()
Usernametxtbx.Text = FileRead4.Value
GlobalVariables.Username = Usernametxtbx.Text
End If
If FileRead4.Name = "Password" Then
FileRead4.Read()
Passwordtxtbx.Text = FileRead4.Value
GlobalVariables.Password = Passwordtxtbx.Text
End If
End Select
Loop
Else
MainBox.MainTextBox.AppendText(FileName4 & " could not be found. Settings are restored to defaults.")
MainBox.Logging(Date.Now & FileName4 & " could not be found. Settings are restored to defaults.")
End If
FileRead4.Close()
End Sub
Public Sub createNode3(ByVal Username As String, ByVal Password As String, ByVal writer As XmlTextWriter)
'On Error Resume Next
writer.WriteStartElement("Username_Password")
writer.WriteStartElement("Username")
writer.WriteString(Username)
writer.WriteEndElement()
writer.WriteStartElement("Password")
writer.WriteString(Password)
writer.WriteEndElement()
writer.WriteEndElement()
End Sub

Contact form is not sending email to my gmail acount

I have created a simple form using Visual Studio 2012 but it's not sending email to my gmail account, the page runs fine but when I hit send button I get error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. j8sm1567623paz.30
Description: An unhanded exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. j8sm1567623paz.30
Source Error:
Line 14:
Line 15:
Line 16: mailClient.Send(message)
Line 17:
Line 18:
Source File: C:\Website SVN II\test\contact.aspx.vb Line: 16
Sources:
Imports System.Net.Mail
Partial Class contact
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
sendMail(txtEmail.Text, txtMessage.Text)
End Sub
Protected Sub sendMail(ByVal From As String, ByVal body As String)
Dim mailservername As String = "smtp.gmail.com"
Dim message As MailMessage = New MailMessage(From, "nabeel.f#gmail.com", "feedback", body)
Dim mailClient As SmtpClient = New SmtpClient
mailClient.Host = mailservername
mailClient.Send(message)
message.Dispose()
End Sub
End Class
HTML.
first name
<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
<br />
<br />
last name
<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
<br />
<br />
email
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<br />
<br />
message:
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Send" />
Two things:
You need to use HTTPS.
You need to provide credentials for your account.
Here's a C# example from here:
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
vb.net version:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim SmtpServer As New SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential
("xyz#gmail.com", "password")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
mail = New MailMessage()
Dim addr() As String = TextBox1.Text.Split(",")
Try
mail.From = New MailAddress("xyz#gmail.com",
"Web Developers", System.Text.Encoding.UTF8)
Dim i As Byte
For i = 0 To addr.Length - 1
mail.To.Add(addr(i))
Next
mail.Subject = TextBox3.Text
mail.Body = TextBox4.Text
If ListBox1.Items.Count <> 0 Then
For i = 0 To ListBox1.Items.Count - 1
mail.Attachments.Add(New Attachment
(ListBox1.Items.Item(i)))
Next
End If
mail.DeliveryNotificationOptions =
DeliveryNotificationOptions.OnFailure
mail.ReplyTo = New MailAddress(TextBox1.Text)
SmtpServer.Send(mail)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub

Send multiple attachments in a folder, not just a specific filename...via email

I have managed to send an email with an attachment that is in a specific location and named specifically ("C:\New\Log.txt")
However, I want to be able to send an email with all the attachments in a given folder no mater what they are called.
All variable settings are configured elsewhere in the project using my.settings and i would like similar for the folder destination i.e. my.settings.fileloc1 for the location of the files
Below is my current code. I'm pretty sure it will involve getfiles, but am running on empty....please help!
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New _
Net.NetworkCredential(My.Settings.SMTPuser, My.Settings.SMTPuser)
SmtpServer.Port = My.Settings.SMTPPort
SmtpServer.Host = My.Settings.SMTPHost
mail = New MailMessage()
mail.From = New MailAddress(My.Settings.from)
mail.To.Add(My.Settings.recipient)
mail.Subject = My.Settings.subject
mail.Body = My.Settings.body
Dim Attach As Net.Mail.Attachment = New Net.Mail.Attachment("C:\New\Log.txt")
'^^The above needs to be an actual file
'^^I want it to select all files in a given folder and attach them!
mail.Attachments.Add(Attach)
SmtpServer.Send(mail)
MsgBox("Mail Sent")
Catch ex As Exception
MsgBox("Email Settings are either incomplete or incorrect" & vbNewLine & "Please see below details:" & vbNewLine & vbNewLine & ex.ToString)
End Try
End Sub
Thanks for anything you can come up with :)
Try a For Each loop looking for all files in System.IO.Directory.GetFiles()
' ...
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
SmtpServer.Send(mail)
' ...

Formatting Dataset results in email

I have a program that on load will load the dataset with info from a query. I then send the information in an email. Everything is working correctly except the output. The output is wrapped and not in table format. If I debug the program and paste the "Value" of "Payouts" into a txt document and save it as an html file it is formatted correctly (Shows in table form). Here is my Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
Me.Paid_Out_TbTableAdapter.Fill(Me.DataDeliveryServiceDataSet.Paid_Out_Tb)
Dim payouts = _
<html>
<body>
<table>
<tr><th>My First Column Header</th><th>My Second Column Header</th></tr>
<%= From paidOut In Me.DataDeliveryServiceDataSet.Paid_Out_Tb.AsEnumerable _
Select <tr><td><%= paidOut.Store_Id %></td><td><%= paidOut.Paid_Out_Comment %></td></tr> %>
</table>
</body>
</html>
SmtpServer.Credentials = New _
Net.NetworkCredential("****", "****")
SmtpServer.Port = 25
SmtpServer.Host = "*****"
mail = New MailMessage()
mail.From = New MailAddress("*#*.com")
mail.To.Add("*#*.com")
mail.Subject = "Test Mail"
mail.IsBodyHtml = True
mail.Body = payouts
SmtpServer.Send(mail)
MsgBox("mail send")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here what is sent in an email as the body:
My First Column HeaderMy Second Column Header4567OFFICE SUPPLIES4567REIMBUSEMENT FOR SERVICE PER ROB PER INCIDENT REPORT4567REFUND FOR SERVICE INVOICE# **4567OFFICE SUPPLIES AND GATORADE
As you can see it's just wrapped and not formatted... How can I get the body to be either in TXT format as a table, or in HTML Format as a table.
The CStr(XElement) function just returns the content of the element. Use:
mail.body=payouts.ToString()