Email doesn't maintain formatting after sending VB.NET - vb.net

I am using EASendmail to send emails.The email body is a rich textbox.If i do formatting e.g. One line below another and send the email,the email loses it's formatting. For example if type this :
Hello,
How are you ?
in the rich text box and send it,then it becomes :
Hello,How are you
How do i maintain the text formatting ? And one more thing, if i add any image to my rich textbox, the email body doesn't keep the image ..I mean , the receiver only receives the texts of the email body, not the image. How to fix these issues ?
My code to send email is :
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New EASendMail.SmtpClient()
oMail.From = fromtxt.Text
oMail.To = New AddressCollection(totxt.Text)
oMail.Subject = subjecttxt.Text
oMail.HtmlBody = bodytxt.Text
Dim oServer As New SmtpServer(MailConfig.host.Text)
oServer.Port = MailConfig.port.Text
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
oServer.User = fromtxt.Text
oServer.Password = MailConfig.password.Text
oSmtp.SendMail(oServer, oMail)
EDIT
I even tried :
oMail.HtmlBody = "<html><body>" + bodytxt.Text + "</body></html>"
But no results

This is an easy fix .
All i had to do is convert my RTF to HTML and then send it..RTF-TO-HTML-CONVERTER
After downloading the project files, reference must be added to the .dll files in the bin folder.Then :
Imports Itenso.Rtf.Converter.Html
Imports Itenso.Rtf.Support
Imports Itenso.Rtf
Dim rr As String = bodytxt.Rtf.Replace("\0", "")
Dim rtfDocument As IRtfDocument = RtfInterpreterTool.BuildDoc(rr)
Dim htmlConverter As New RtfHtmlConverter(rtfDocument)
Dim html1 As String = htmlConverter.Convert()
' my other codes in-between(read my post)
oMail.HtmlBody = html1

Related

VBA Excel: Retrieve/display email using Gmail API on excel

I research regarding retrieving or displaying emails from gmail without using outlook and it led me here on using Gmail API. I'm confused because I don't have idea on how to solve my problem.
Here's the code:
Attribute VB_Name = "Gmail"
' Setup client and authenticator (cached between requests)
Private pGmailClient As WebClient
Private Property Get GmailClient() As WebClient
If pGmailClient Is Nothing Then
' Create client with base url that is appended to all requests
Set pGmailClient = New WebClient
pGmailClient.BaseUrl = "https://www.googleapis.com/gmail/v1/"
' Use the pre-made GoogleAuthenticator found in authenticators/ folder
' - Automatically uses Google's OAuth approach including login screen
' - Get API client id and secret from https://console.developers.google.com/
' - https://github.com/timhall/Excel-REST/wiki/Google-APIs for more info
Dim Auth As New GoogleAuthenticator
Auth.Setup CStr(Credentials.Values("Google")("id")), CStr(Credentials.Values("Google")("secret"))
Auth.AddScope "https://www.googleapis.com/auth/gmail.readonly"
Auth.Login
Set pGmailClient.Authenticator = Auth
End If
Set GmailClient = pGmailClient
End Property
' Load messages for inbox
Function LoadInbox() As Collection
Set LoadInbox = New Collection
' Create inbox request with userId and querystring for inbox label
Dim Request As New WebRequest
Request.Resource = "users/{userId}/messages"
Request.AddUrlSegment "userId", "me"
Request.AddQuerystringParam "q", "label:inbox"
Dim Response As WebResponse
Set Response = GmailClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Dim MessageInfo As Dictionary
Dim Message As Dictionary
For Each MessageInfo In Response.Data("messages")
' Load full messages for each id
Set Message = LoadMessage(MessageInfo("id"))
If Not Message Is Nothing Then
LoadInbox.Add Message
End If
Next MessageInfo
End If
End Function
' Load message details
Function LoadMessage(MessageId As String) As Dictionary
Dim Request As New WebRequest
Request.Resource = "users/{userId}/messages/{messageId}"
Request.AddUrlSegment "userId", "me"
Request.AddUrlSegment "messageId", MessageId
Dim Response As WebResponse
Set Response = GmailClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Set LoadMessage = New Dictionary
' Pull out relevant parts of message (from, to, and subject from headers)
LoadMessage.Add "snippet", Response.Data("snippet")
Dim Header As Dictionary
For Each Header In Response.Data("payload")("headers")
Select Case Header("name")
Case "From"
LoadMessage.Add "from", Header("value")
Case "To"
LoadMessage.Add "to", Header("value")
Case "Subject"
LoadMessage.Add "subject", Header("value")
End Select
Next Header
End If
End Function
Sub Test()
Dim Message As Dictionary
For Each Message In LoadInbox
Debug.Print "From: " & Message("from") & ", Subject: " & Message("subject")
Debug.Print Message("snippet") & vbNewLine
Next Message
End Sub
I'm using the blank file from this GitHub Link that enables this code above. I was stuck on this error:
Still I don't have the idea what's the output of this API because it's my first time using this one. I have my id and secret already from Gmail API i just removed it from the code. I guess it was really hard if I don't have someone I can do brainstorming regarding on this matter.
Hoping someone have encountered this problem or anyone is interested. Thanks.

Send mht file in body email

Hello I am using SendGridMessage() object with VB.net to send emails through SendGrid SMTP server.
I have a .mht file that i want to send in the mail body...
I know that is possible to send pure html in a mail body but when i read the MHT file and put it on the mail body, it appears all messed up like this:
And i wanted to look it like this:
This is my code:
Dim myMsg As New SendGridMessage()
myMsg.AddTo("email#email.com")
myMsg.From = New MailAddress(ApiEmail, ApiUserName)
myMsg.Subject = "Test with MHT file"
myMsg.Html = ""
Dim fso As New FileSystemObject
Dim ts As TextStream
'Open file.
ts = fso.OpenTextFile(sPath)
'Loop while not at the end of the file.
Do While Not ts.AtEndOfStream
myMsg.Html += ts.ReadLine
Loop
'Close the file.
ts.Close()
Dim credentials = New NetworkCredential(ApiUser, ApiKey)
Dim transportWeb = New Web(credentials)
transportWeb.DeliverAsync(myMsg)
You need to convert the .MHT file to regular HTML first to use it in this way. MHT contains metadata and is structured differently than HTML, so you can't use it in a parameter that expects HTML. MHT is more like a MIME message. If you want to deal with MIME via MHT, then sending over SMTP will be easier.

SendMail Help in VB

I developed a sendmail program for support which works great. What I am trying to do now is add a history page, which will show my users what support requests they have sent previously. I plan on use My.Settings to save the each email sent from my program.
Here is my code for the SendMail button which sends me mail:
If TextBox1.Text = "" Then
MsgBox("Please describe the issue you're having Bender, I'm not a mindreader!")
Exit Sub
Else
lblpleasewait.Visible = True
delay(2000)
Dim Recipients As New List(Of String)
Recipients.Add("johndoe#yahoo.com")
Dim FromEmailAddress As String = Recipients(0)
Dim Subject As String = "IT Help!"
Dim Body As String = TextBox1.Text
Dim UserName As String = My.Settings.txtboxUN
Dim Password As String = My.Settings.txtboxPW
Dim Port As Integer = My.Settings.txtboxSMTPPort
Dim Server As String = My.Settings.txtboxSMTP
Dim Attachments As New List(Of String)
MsgBox(SendEmail(Recipients, FromEmailAddress, Subject, Body, UserName, Password, Server, Port, Attachments))
lblpleasewait.Visible = False
TextBox1.Text = ""
TextBox1.Focus()
'This is where the beginning of my code is to send it to the history form.
Dim str(2) As String
Dim itm As ListViewItem
str(0) = Today + " - " + TimeOfDay
str(1) = Body
itm = New ListViewItem(str)
GTSMailHistory.ListView1.Items.Add(itm)
My.Settings.logDate = str(0)
My.Settings.logIssue = str(1)
My.Settings.Save()
End If
As you can from the above code, the last few lines is where I add the Body of the email and the time of day and add it to my listview I have on another form (GTSMailHistory).
My problem is this, that code above sending it over to the other form is saving, but is overwritten with each new email. Its basically not appending new emails to the list, just writing over the first.
The only code I have on the history form is on the LOAD function which is below:
Private Sub GTSMailHistory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim str(2) As String
Dim itm As ListViewItem
str(0) = My.Settings.logDate
str(1) = My.Settings.logIssue
itm = New ListViewItem(str)
ListView1.Items.Add(itm)
End Sub
I can't leave comments yet so if someone could move this it'd help.
Are you recreating your GTSMailHistory object each pass instead of just once at startup?
Also when saving the date/body to My.Settings you are overwriting the existing values, do you not want these to be lists instead?
In response to your comment:
Joiner, i do want it to be a list. Can i save a listview to my.settings so it remains persistent upon next program launch?
You can use My.Settings to store variables of different types including lists.
In Visual Studio go to:
Project -> Properties -> Settings (Tab) -> Add a setting and its type (browse for more).
See here for an example.
Found sort of an answer. Not really want i want but will suffice right now. I can write this to a textfile and use streamreader to load it to listview.
The below code adds the body and date to listview:
Static i As Integer = 0
Dim newItem As New ListViewItem(Today + " - " + TimeOfDay) '// add text Item.
newItem.SubItems.Add(TextBox2.Text) '// add SubItem.
history.ListView1.Items.Add(newItem) '// add Item to ListView.
i += 1
The below code loads the saved textfile
ListView1.View = View.Details : ListView1.Columns.Add("Date") : ListView1.Columns.Add("Issue")
If IO.File.Exists(myCoolFile) Then '// check if file exists.
Dim myCoolFileLines() As String = IO.File.ReadAllLines(myCoolFile) '// load your file as a string array.
For Each line As String In myCoolFileLines '// loop thru array list.
Dim lineArray() As String = line.Split("#") '// separate by "#" character.
Dim newItem As New ListViewItem(lineArray(0)) '// add text Item.
newItem.SubItems.Add(lineArray(1)) '// add SubItem.
ListView1.Items.Add(newItem) '// add Item to ListView.
Next
End If
On form close it saves my entries:
Dim myWriter As New IO.StreamWriter(myCoolFile)
For Each myItem As ListViewItem In ListView1.Items
myWriter.WriteLine(myItem.Text & "#" & myItem.SubItems(1).Text) '// write Item and SubItem.
Next
myWriter.Close()

Read the first mail in the inbox, save subject content as a text file using pop3client

Am facing a problem while saving the mail as a text file through vb.net. i had done the following code as per my task:-
public sub rearmail()
Dim pop3Client As Pop3Client
If (Session("Pop3Client") Is Nothing) Then
pop3Client = New Pop3Client
pop3Client.Connect("pop.gmail.com", 995, True)
pop3Client.Authenticate("mymail#gmail.com", "password")
Session("Pop3Client") = pop3Client
Else
pop3Client = CType(Session("Pop3Client"), Pop3Client)
End If 'connect to the inbox with username and pass word authentication
Dim message As Message = pop3Client.GetMessage(0)
dim frm as string ' to store from address
dim subj as string ' to store the subject
dim mdate as date ' to store the date and time
frm=message.Headers.From.Address
subj= message.Headers.Subject
mdate=message.Headers.DateSent
'**** no i need to read the mail message and save it as a notepad file ****
end sub
i had tried a lot to read the mail using :-
Dim message As Message = pop3Client.GetMessage(0)
as follows:-
Dim str As MailMessageEventArgs
dim strmsg as string
strmsg=str..Message.Body.ToString 'error null error exception at run time
strmsg=message.MessagePart.Body ' nothing will return
like wise i do a lot with the message object but i fails to achieve the goal, i hope that the experts in this community can help me to overcome the problem,
thanks in advance.....♥
thanks for the one who make a try to solve the problem, i got the solution now i wish to share it with you. here is the code segment to read the mail body content;-
Dim messagePart As MessagePart = message.MessagePart.MessageParts(0)
MsgBox(messagePart.BodyEncoding.GetString(messagePart.Body))

How to put a hyperlink into the email body using vb.net

What im trying to do is add a hyperlink to the body of an email in vb.net. What im getting when i send the email is the link is text. Here is what I doing so far below. Any help would be very much appreciated.
'Accepts two parameters - the username and password for the email client
Dim credentials As New System.Net.NetworkCredential("test#test.net", "test")
smtpClient.Credentials = credentials
Dim body, link As String
link = "http://localhost:" & partUrl & "/test.aspx?autoNum=" & autoNum
body = "Test email." & "<br/><br/>"
body += link
Dim email As New MailMessage
email.From = New MailAddress("test#test.net")
email.Body = body
email.Subject = "test Change/Request Password"
email.To.Add(New MailAddress(toAddress))
smtpClient.Send(email)
You will need to enclose it in a tags.
link = "Click here"
And you need to set
email.IsBodyHtml = true
Try this:
link = "Link"
body = "Test email." & "<br/><br/>"
body += link
The idea (I can't test it now, sorry) is you have to add not the url itself, but the HTML code used to create link.
Remember to set mail body to html with email.IsBodyHtml = True
I believe you need to set
IsBodyHtml = True
Then you can use plain HTML in the body of the e-mail. It's still up to the mail client to display it correctly. I've had a few cases where valid HTML that looked create in my browser was messy in my e-mail.
You haven't identified the body as HTML.
Add:
email.IsBodyHtml = true