Format a string into an email Body Format - vb.net

I am using this code to send an email on my code
in this below code subject and mail body we are getting form dataset and storing in a string .
i didn't have any concern regarding subject but when it comes to body i am facing issue like
for example in my mail body i am having three points i.e, three line
1.some text
2.some text
3.some text
after the mail is triggered my mail body is looking like
1.some text 2.sometex 3.sometext .
here is my piece of code
Try
Dim SmtpServer As New SmtpClient
Dim mail As New MailMessage
SmtpServer.Credentials = New Net.NetworkCredential()
SmtpServer.Port = 25
SmtpServer.Host = "email.host.com"
mail = New MailMessage
mail.From = New MailAddress("myemail#email.com")
mail.To.Add("otheremail#email.com")
mail.Subject = Subject
mailbody= "<html>" & " <body>" & "<p>" _
& String.Join("</p><p>", mailbody.Split({Environment.NewLine},
StringSplitOptions.None)) _
& " </p>" & "</body> " & " </html>"
mail.Body = mailbody
mail.IsBodyHtml=true
SmtpServer.Send(mail)
catch ex As Exception
MsgBox(ex.ToString)
End Try
is there any way where i can get the exact format .
Please check the below screen shot
After generating the mail still i ma getting the mail is lookin like this

Give this a go:
mailbody = _
"<html>" & " <body>" & "<p>" _
& String.Join("</p><p>", mailbody.Split({Environment.NewLine}, StringSplitOptions.None)) _
& " </p>" & "</body> " & " </html>"
The issue was that you were splitting the lines int he mailbody and we weren't closing your HTML tags properly.

You are trying to insert the "Enter" in HTML (that doesn't work) replace that by <br/>
You can also replace the "Environment.NewLine" by <br/>
Use <br/> in HTML to bring the text to the next line.

Related

Multiple sms send in AT commands VB.NET

I'm trying to send many or bulk sms using AT Command. I try send all number inside the datagrid but only first number is sending.
this is my code
Dim sql As New MySqlDataAdapter("select StudentID, StudentName,StudentContact, DueDate FROM issue inner join student on student.StudentID = issue.Student ", conn)
Dim ds As New DataSet
sql.Fill(ds, 0)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim wholenum As String
Dim wholesms As String
wholenum = ds.Tables(0).Rows(i).Item(2).ToString
wholesms = "Hello " & ds.Tables(0).Rows(i).Item(1).ToString & ", this is your Due Date " & ds.Tables(0).Rows(i).Item(3).ToString & " pls return it on your due date"
If SerialPort1.IsOpen Then
Try
With SerialPort1
.Write("AT" & vbCrLf)
.Write("AT+CMGF=1" & vbCrLf)
.Write("AT+CMGS=" & Chr(34) & wholenum & Chr(34) & vbCrLf)
.Write(wholesms & Chr(26))
MsgBox("Success sa SEND")
'update one
'Call ConnectDatabase()
'com = New MySqlCommand("UPDATE issue SET Sent='1' ", conn)
'com.ExecuteNonQuery()
'Call DisconnectDatabase()
End With
Catch ex As Exception
MsgBox("Bad Signal or No load")
End Try
Else
MsgBox("Pls insert a modem")
End If
I think the looping is working 'cuz it apppears the successful message of how many inside in the datagrid view. But it only send the first number.
You need to fix your AT command handling significantly. First of all you need to read and parse everything the modem sends back to you after sending a AT command line (which by the way should be terminated with just "\r" and not vbCrLf).
You should never start sending a new command line before you have received the Final result code. And for AT+CMGS specifically you should never send the sms payload before you have received the "\r\n >" prefix.
These issues are covered in this and this answer. But the very first thing you should to is to read all of the text in chapter 5 in the V.250 specification. It is a really important document when working with AT commands.

Read Delivery Failure email ID

I have a macro for reading Email body which is triggered from MS Outlook rules.
Every Email is read but Email from 'Microsoft Outlook' which is a delivery failure email sent by MS exchange server.
I need to read this item to get the email ID which is causing the bounce back.
Sub VBS_GetEmailFromBodyText(anItem AsOutlook.MailItem)
'Email parameters
fromID = anItem.SenderName
toList = anItem.To
emailsubject = anItem.Subject
emailBody = Left(anItem.Body, 10)
receiveTime = anItem.ReceivedTime
'create query String
sqlQuery = "INSERT INTO [myDB].[dbo].[VBStestTable](fromID,toList,emailsubject,emailBody,receiveTime) Values('"& fromID & "','"& toList & "','"& emailsubject & "','"& emailBody & "','"& receiveTime & "')"
'SQL connection code
'------------------------
ConstadOpenStatic = 3
ConstadLockOptimistic = 3
objConnection = CreateObject("ADODB.Connection")
objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open( _
"Provider = SQLOLEDB; "& _
"Data Source=MyServer;"& _
"Trusted_Connection=Yes;"& _
"InitialCatalog=MyDB;"& _
"User ID=myUser;Password=myPassword;")
'-------------------------
'ended SQL Connection code
 
'RUN SQL Query --Insert records into DB
objRecordSet.Open(sqlQuery, _
objConnection, adOpenStatic, adLockOptimistic)
' Close the DB Connection
objConnection.Close()  
EndSub
What code do you use now for reading and parsing the message body now?
The Outlook object model provides three main ways for working with item bodies:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item.
Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to set up the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies. It us up to you which way is to choose to read the message body.

VB.Net, sending emails out uniquely

im an intern at a packaging company and we have an interface that sends out summary emails out to several people on mondays. There are about 70 groups that the code sees. every group has a specific section that people enter a log in. if you are a recipient in that group on monday you will recieve a summary email of all the active logs entered for groups you are in. if user A is in group 1 and 2, he or she should recieve 2 emails with active logs pretaining to those 2 groups. Problem is he or she is signed up in all 70 groups and if there are only 2 active logs from group 1 and 2 she recieves 70 identical emails with summaries containing active logs for those 2 groups. here is the code.
Private Sub SendEmails()
Try
Dim message As New PCA.Core.Messaging.Message(PCA.Core.Messaging.MessageTypes.JumperLog)
'Dim distLists As List(Of PCA.Core.DistributionList) = (From r In Trident.Core.Globals.TridentApp.ApplicationCache.DistributionLists.DistributionLists Where r.ID.Contains("JL_")).ToList
Dim distLists As List(Of PCA.Core.DistributionList) = (From r In PCA.Core.DistributionList.GetDistributionLists Where r.Id.Contains("JL_")).ToList
For Each distlist As PCA.Core.DistributionList In distLists
Dim recipients As System.Collections.Generic.List(Of Trident.Core.User)
recipients = Trident.Core.Core.Message.GetTridentDistributionList("TRIMAINT", distlist.Id)
If recipients.Count > 0 Then
message.Recipients.AddRange(recipients)
End If
Next
If message.Recipients.Count = 0 Then Exit Sub
Dim ds As New DataSet
Dim dbConn As New Trident.Core.DBConnection
Dim sql As String = "SELECT * FROM ***.Maintenance.JumperLogs WHERE Removed <> 1 AND Plant = #Plant ORDER BY InstallDate "
dbConn("#Plant") = Trident.Core.Globals.TridentApp.DefaultPlant.Plant
Dim tmpJL As Trident.Objects.Maintenance.JumperLogs.JumperLog
message.Subject = "Jumper Log - Active Jumpers"
ds = dbConn.FillDataSet(sql)
If ds.Tables(0).Rows.Count = 0 Then Exit Sub
For Each dr As DataRow In ds.Tables(0).Rows
tmpJL = New Trident.Objects.Maintenance.JumperLogs.JumperLog(dr)
message.Body += "Jumper Log # " & tmpJL.LogId & " - Installed: " & tmpJL.InstallDate & vbCrLf
message.Body += "Mill: " & Trident.Core.Globals.TridentApp.DefaultPlant.Description & vbCrLf
message.Body += "Facility: " & tmpJL.FacilityObject.Description & vbCrLf
If Not tmpJL.MachineAreaObject Is Nothing Then
message.Body += "Area: " & tmpJL.MachineAreaObject.Description & vbCrLf
End If
If Not tmpJL.LocationObject Is Nothing Then
message.Body += "Location: " & tmpJL.LocationObject.Description & vbCrLf
End If
If Not tmpJL.EquipmentObject Is Nothing Then
message.Body += "Equipment: " & tmpJL.EquipmentObject.Description & vbCrLf
End If
message.Body += "Installed By: " & tmpJL.InstalledBy.FullName & vbCrLf
'message.Body += "Install Date: " & tmpJL.InstallDate & vbCrLf
message.Body += "Tag: " & tmpJL.Tag & vbCrLf
message.Body += "Tag Attached To: " & tmpJL.TagAttachedTo & vbCrLf
message.Body += "Work Order: " & tmpJL.WorkOrder & vbCrLf
message.Body += vbCrLf
message.Body += "Reason: " & tmpJL.Reasons.ToUpper & vbCrLf
message.Body += vbCrLf
message.Body += "---------------------------------------------------------------------------------------------------------------------------------------------------" & vbCrLf
message.Body += vbCrLf
Next
message.Send()
Catch ex As Exception
Throw New PCA.Core.Exceptions.PCAErrorException(ex)
End Try
End Sub
Now i think that modifying the if statement that initializes the range, might do it?
Ok a user that is in "JL_001" group recieved a summary email on monday that JL_001 group is label by facilities and this one is called #1paper machine" since. he is only in one group that paper machine group he got one email with only one active jumperlog which happens to be from his facility (#1 paper Machine.) Now this is the issue, there is a group of users that have all been added to groups "JL_001 to JL_070". since there was only one acitve log entered that previous week on monday they should only get one summary email because they are also in the #1 paper machine facility group(JL_001). they shouldnt receive anything else from any other group because there were no active logs from those groups yet they recieved 70 emails of that same summary pretaining to JL_001. Does this help clear it up?
You should be building the message body for each recipient, and then send your messages by recipient instead of group. You could do this by following these steps:
Create a global list of recipients
Get the list of recipients a group
Loop through the recipients list. If the recipient already exists, append the additional message body to their record. If not, create a new record in the global list.
Repeat steps 2-3 through all groups.
Loop through the global list of recipients, and send one message per recipient.

VB.NET Database Retrieval

I have a VB.NET application that has instant messaging-like functionality with a database. It can retrieve the values just fine, but the problem is the formatting isnt coming out right. I want the format to be as follows:
Sender: Message
(so...)
David: Hey guys
What I've tried below doesn't get me the result I'm looking for, it just prints the sender at the top of the rich textbox in my application and the message at the bottom, does anyone have any ideas?
'-------------------Retreives the message-------------------------------------------------------------
Dim sqlStr As String = "SELECT * FROM dojodb.chats"
Dim chatcommand As New MySqlCommand(sqlStr, MysqlConn)
Dim rdr As MySqlDataReader = chatcommand.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(rdr)
'-------For every row, print the message, skip a line, and add 1 so it goes to next msg-- ------
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strSender &= CStr(tbl.Rows(rowIndex)("Sender")) & vbNewLine
strMessage &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut = strSender + ": " + strMessage
Next
txtGroupChat.Text = strOutPut
'Keeps the richtextbox scrolled to the bottom so that most recent msg is always shown
txtGroupChat.SelectionStart = txtGroupChat.Text.Length
txtGroupChat.ScrollToCaret()
strOutPut = "" 'clearing the string so that it does not print out duplicate info next time
strSender = ""
strMessage = ""
'-------------------------End Retrive---------------------------------------
I feel a bit embarrassed posting this, but...
strSender = CStr(tbl.Rows(rowIndex)("Sender")) & ": "
strMessage = CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
strOutPut &= strSender & strMessage
What do you think vbNewLine does? Also, be careful of &=

"Pinging" an email address using VB.Net coding

Is there a way in VB.Net to "Ping" an email address to see if that email is a real one that does not give any errors?
If yes, can you show what the VB.Net coding looks like to implement this?
I plan to use this in an app that requires the Customer email and it would be nice to validate it as the call taker enters it into a form before saving the Customer details.
Here is the code we are using to send an email promotion to all of the customers in our customer table:
Private Sub RibbonButtonSendTestEmail_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButtonSendTestEmail.Click
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
Dim strSqlStatement As String = "Select CustomerName, Email " & _
"From Customers "
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
With objSqlCommand
' Open the SqlConnection before executing the query.
'---------------------------------------------------
Cursor = Cursors.WaitCursor
ObjConnection.Open()
Dim objDataReader As SqlDataReader = .ExecuteReader()
' Go through all the customers and send out the promotion emails.
'----------------------------------------------------------------
If objDataReader.HasRows Then
SmtpServer.Host = TextBoxSMTPServer.Text
SmtpServer.Port = TextBoxPort.Text
If TextBoxUseSSL.Text = "Yes" Then
SmtpServer.EnableSsl = True
Else
SmtpServer.EnableSsl = False
End If
If TextBoxUseDefaultCredentials.Text = "Yes" Then
SmtpServer.UseDefaultCredentials = True
Else
SmtpServer.UseDefaultCredentials = False
End If
SmtpServer.Credentials = New Net.NetworkCredential(TextBoxUserName.Text, TextBoxPassword.Text)
While objDataReader.Read()
Try
mail.To.Add(objDataReader("Email").ToString)
mail.From = New MailAddress(TextBoxEmailFrom.Text)
mail.Subject = "Promotion: " & TextBoxID.Text
mail.Body = "Dear " & objDataReader("CustomerName") & "," & vbCrLf & vbCrLf & TextBoxPromotionBodyText.Text
SmtpServer.Send(mail)
Catch exSMTP As SmtpException
MessageBox.Show("Sorry, I could not send an email for: " & _
vbCrLf & objDataReader("CustomerName") & "." & vbCrLf & _
"Please make sure it is correct.", _
"Error")
Catch exFormat As FormatException
MessageBox.Show("Sorry, this customer's email is not properly formatted: " & _
vbCrLf & objDataReader("CustomerName") & "." & vbCrLf & _
"Please make sure it is correct.", _
"Error")
End Try
End While
LabelEmail.Text = "Sent email promotions to the customers."
End If
objDataReader.Close()
ObjConnection.Close()
Cursor = Cursors.Default
End With ' objSqlCommand
End Using ' objSqlCommand
End Sub
Yes it's perfectly possible:
1 DNS Lookup the MX records for the domain
There may be multiples, you can pick anyone, although technically the one with the lowest preference indicator is the prefered one.
2 TCP Connect to the mail server (port 25)
Say hello: HELO
Identify yourself: mail from:<test#example.com>
Say who you're writing to: rcpt to<testaddress#example.com>
At this point the server will reply with a response, you'll get an OK or a 550 error with a message (like: The email account that you tried to reach does not exist)
Disconnect and the message will be dropped.
But dude, you want the VB code to do this? You just need a DNS talking piece and TCP connection building piece (or likely there are some SMTP libraries out there that'll do all this for you - or provide you with inspiration to figure it out yourself). Don't forget you can probably find a C# code example that does it and use Visual Studio's conversion tool to switch it to VB.
Note
Many domains have black holes/catch alls... the former will accept any email address and just delete it if it's invalid, the latter will accept any email address and forward them to a central account (no guarantees as to what happens then... sell the sender's address to spammers?) In both cases you won't get the 550 message, so you can never be certain.
There most reliable way to do this is to send a test email and have the recipient verify receipt by clicking on a link, which you then read and mark the email as active.
You should do primitive checks on the syntax of the email using regular expressions, but beyond that the most reliable way to validate an email is to attempt delivery and confirm the receipt.