Sending Mail with headers and saved in user's Sent Items VB.NET - vb.net

I use this code to send an email using SMTP
Dim clnt As New System.Net.Mail.SmtpClient
clnt.UseDefaultCredentials = False
clnt = New System.Net.Mail.SmtpClient(gate)
Dim auth_info As System.Net.NetworkCredential = New System.Net.NetworkCredential(toAddress, pass)
'// MESSAGE SETUP
Dim msg As New System.Net.Mail.MailMessage(fromAddress, toAddress)
If msg.To.Count = 0 Then Return False
msg.CC.Clear()
'// SEND A COPY TO SENDER
'msg.Bcc.Add(auth_info.UserName)
msg.Bcc.Add(fromAddress)
'msg.DeliveryNotificationOptions = Net.Mail.DeliveryNotificationOptions.OnFailure
'msg.DeliveryNotificationOptions = Net.Mail.DeliveryNotificationOptions.OnSuccess
msg.Headers.Add("Disposition-Notification-To", fromAddress)
msg.Subject = subject
msg.Body = msgbody
msg.IsBodyHtml = True
Dim serverBusy As Boolean = True
While serverBusy
Try
clnt.Send(msg)
serverBusy = False
Catch
serverBusy = True
End Try
End While
With this code the copy of the email is sent to the sender because
of the bcc property, but in the 'incoming folder'.
Because of headers property I achieve to be informed if the receiver
read the message. A dialog box asks the receiver if he wants the
sender to be informed that he read the email message, If he
presses OK then the sender is informed with a new message. The
problem is that with this implementation the sender is asked with
the same dialog box when he opens the the copy of the message(bcc
property).

Related

Send newsletter HTML Email with pictures as body

I'm new to this group and i have one question. how can i attach pictures on the HTML newsletter that i have. when i send the newsletter everything goes well but the pictures are not showing on the email. please help. this is the code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Body As String = GetWebPageContent(Sender_email, Message)
Dim Mail As New MailMessage
Mail.Subject = "Test HTML"
Mail.To.Add(to_email)
Mail.From = New MailAddress(Sender_email)
Mail.Body = Body
Mail.IsBodyHtml = True
Mail.Priority = MailPriority.Normal
Dim SMTP As New SmtpClient(SMTP_Confg)
SMTP.EnableSsl = False
SMTP.Credentials = New System.Net.NetworkCredential(Sender_email, Password)
SMTP.Port = Port_Num
Try
SMTP.Send(Mail)
MsgBox("Successfully Sent!!!")
Catch ex As Exception
MessageBox.Show(" - your confermation email is not sent! " & vbNewLine & " Please contact your Administrator!")
End Try
End Sub
Private Function GetWebPageContent(ByVal recipient As String, ByVal customMsg As String) As String
Dim objStreamReader As New StreamReader("C:\Users\alex.GFH\Desktop\Email\beefree-s09uuvnlono.HTML")
'read html template file'
Dim bodyMsg As String = objStreamReader.ReadToEnd()
Return bodyMsg
End Function
It looks like you're copying the raw HTML from this file:
"C:\Users\alex.GFH\Desktop\Email\beefree-s09uuvnlono.HTML"
As the message body of your email.
My psychic powers tell me that you've got <img> tags inside your HTML that are pointing to relative locations. e.g. <img src="picture.jpg"/>. As such when the HTML email is opened in someone else's browser or mail app, the renderer has no idea where to fetch "picture.jpg" from.
And even if it did have the full URL, most mail apps won't fetch URL images by default until the user acknowledges the privacy risk.
I think if you want your images to just show up when the mail is opened, inline the image bytes directly into the <img> tag. You base 64-encode the image and stick on a header (e.g. data:image/png;base64, or data:image/jpeg;base64,. That becomes the src attribute.
E.g:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
More details here: https://www.rfc-editor.org/rfc/rfc2397

VB.Net Email not putting copy in sent folder

I'm going mad here!
Sending emails in VB.Net is working fine, even the read/delivery receipts are working. What it's not doing, is putting a copy of the email it sends in the sent folder. Is there something else I need to do as I've searched high a low for a solution but can't see anything.
EMail.From = New MailAddress(sSENDERaddress)
EMail.Body = sMessage
EMail.Subject = sSubject
If sAttached <> "" Then
Dim mAttachment As New Attachment(sAttached)
EMail.Attachments.Add(mAttachment)
End If
EMail.Headers.Add("Return-Receip-To", sSENDERaddress)
EMail.Headers.Add("Disposition-Notification-To", sSENDERaddress)
EMail.Headers.Add("Return-Path", sSENDERaddress)
EMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure Or DeliveryNotificationOptions.OnSuccess ' this will send an email to the SENDER'S email address confirming that the original email was sent. If the sender doesn't get the email, then it didn't go. Simples
SMTPServer.Host = GetMailServerAddress()
SMTPServer.Port = GetMailPort()
SMTPServer.Credentials = Authentication
Try
SMTPServer.Send(EMail)
'EMail.Dispose()
bRET = True
Catch ex As Exception
''debug.Print(ex.Message)
ExceptIt(ex.Message)
'EMail.Dispose()
bRET = False
End Try
I've found a few more posts on this subject, and it looks like you can't do it. The only Heath Robinson solution is to add a BCC to my sending address...
UPDATE: For those interested, it's not an SMTP function, but an IMAP one. I suppose, if you want to, you can spend hours working the code out for this, but I found this
https://www.example-code.com/vbnet/sendWithCopyToSentMailbox.asp
Where you simply append to the sent items...
' Now use Chilkat IMAP to save the email to Inbox.Sent
Dim imap As New Chilkat.Imap
' Connect to an IMAP server.
' Use TLS
imap.Ssl = True
imap.Port = 993
success = imap.Connect("mail.mydomain.com")
If (success <> True) Then
Console.WriteLine(imap.LastErrorText)
Exit Sub
End If
' Login
success = imap.Login("myLogin","myPassword")
If (success <> True) Then
Console.WriteLine(imap.LastErrorText)
Exit Sub
End If
' The AppendMail method uploads an email to an IMAP server
' and saves it in the mailbox specified:
success = imap.AppendMail("Inbox.Sent",email)
If (success <> True) Then
Console.WriteLine(imap.LastErrorText)
Exit Sub
End If
Console.WriteLine("Mail saved to Inbox.Sent")

VB Authenticate User In Outlook Web App

I currently have a mail system using Microsoft's exchange server (OWA). I am trying to authenticate a user and send an email using pure Visual Basic code.
I have been trying to use a library called Aspose, however; I have no idea if I'm on the right track. I can not get it to work and I am not sure (since this is a company mail server) whether it's the server or it's my code.
Currently I have,
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Create instance of ExchangeClient class by giving credentials
Dim client As Aspose.Email.Exchange.ExchangeClient = New Aspose.Email.Exchange.ExchangeClient("https://MAILSERVER.com/username/", "username", "password", "https://MAILSERVER.com/")
' Create instance of type MailMessage
Dim msg As Aspose.Email.Mail.MailMessage = New Aspose.Email.Mail.MailMessage()
msg.From = "username#MAILSERVER.com"
msg.To = "receivingemail#gmail.com"
msg.Subject = "test"
msg.HtmlBody = "test"
' Send the message
Try
client.Send(msg)
Console.WriteLine("made it")
Catch ex As Exception
Console.WriteLine("failed")
End Try
End Sub
I have obviously changed the username, password, and server name fields to generic ones but with (what I think is the right credentials) the output is always failed.
Can anybody help me out please?
Here is what I use:
Public Shared Function SendEMail(MailMessage As System.Net.Mail.MailMessage) As String
ErrorMess = ""
' Default the from address, just in case is was left out.
If MailMessage.From.Address = "" Then
MailMessage.From = New Net.Mail.MailAddress("donotreply#MAILSERVER.com")
End If
' Check for at least one address
If MailMessage.To.Count = 0 AndAlso MailMessage.CC.Count = 0 AndAlso MailMessage.Bcc.Count = 0 Then
ErrorMess = "No Addresses Specified"
Return ErrorMess
End If
' Create a SMTP connedction to the exchange 2010 load balancer.
Dim SMTPClient As New System.Net.Mail.SmtpClient("MAILSERVER.com")
Try
Dim ValidUserCredential As New System.Net.NetworkCredential
ValidUserCredential.Domain = "MAILSERVER.com"
ValidUserCredential.UserName = My.Resources.EmailUserName
ValidUserCredential.Password = My.Resources.EmailPassword
SMTPClient.UseDefaultCredentials = False
SMTPClient.Credentials = ValidUserCredential
SMTPClient.Send(MailMessage)
Return "Mail Sent"
Catch ex As Exception
ErrorMess = ex.Message & " " & ex.InnerException.ToString
Return ErrorMess
End Try
End Function
The ExchangeClient class is used to connect to Exchange server using the WebDav protocol and is used with Exchange Server 2003 and 2007. For OWA, you need to use the IEWSClient interface as shown in the following sample code. It has an Office365 test account that you can use to send a test email (the test account is solely for testing purpose and is not property of Aspose. I just created it for assisting you in testing the functionality). Please try it and if you face any problem, you may share the porblem on Aspose.Email forum for further assistance.
' Create instance of IEWSClient class by giving credentials
Dim client As IEWSClient = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "UserTwo#ASE1984.onmicrosoft.com", "Aspose1234", "")
' Create instance of type MailMessage
Dim msg As New MailMessage()
msg.From = "UserTwo#ASE1984.onmicrosoft.com"
msg.[To] = "receiver#gmail.com"
msg.Subject = "Sending message from exchange server"
msg.IsBodyHtml = True
msg.HtmlBody = "<h3>sending message from exchange server</h3>"
' Send the message
client.Send(msg)
I work with Aspose as Developer evangelist.

Using Sleep in VB.NET

I have a kind of simple issue, I have a section of code that sends out a test email and just before this process occurs, I'd like a marquee progress bar to appear, indicating that something is happening.
However, the progress bar does not appear until the test email has been sent.
I've tried experimenting with the Sleep function, but the progress bar still wont appear until after the test email sends.
Does anyone know why?
Code: (Note: GroupBoxTesting contains the Progress bar)
Private Sub BTMsendmailtest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTMsendmailtest.Click
GroupBoxTesting.Visible = True
Threading.Thread.Sleep(500)
Try
Dim Mail As New MailMessage
Mail.Subject = "Test email for Email Alerts!"
Mail.To.Add(TXTemailaddy.Text)
Mail.From = New MailAddress(TXTsmtpusr.Text)
Mail.Body = "This is a test message from Email Alerts!" & Environment.NewLine & Environment.NewLine & "If you are reading this, then Email Alerts! is properly configured."
Dim SMTP As New SmtpClient(TXTsmtpsvr.Text)
If CHKEnableSSL.Checked = True Then
SMTP.EnableSsl = True
Else
SMTP.EnableSsl = False
End If
SMTP.Credentials = New System.Net.NetworkCredential(TXTsmtpusr.Text, TXTsmtppwd.Text)
SMTP.Port = TXTsmtpport.Text
SMTP.Send(Mail)
SendingPB.Value = False
MessageBox.Show("A test email has been sent to " & TXTemailaddy.Text & " from " & TXTsmtpusr.Text & "." & Environment.NewLine & Environment.NewLine & "If you did not recieve an email, please check your settings and try again.", "Test Email")
GroupBoxTesting.Visible = False
Catch ex1 As Exception
SendingPB.Value = False
GroupBoxTesting.Visible = False
MessageBox.Show(ex1.Message)
Return
End Try
End Sub
You've told the UI thread (which is the thread your code as it is is currently running on) to go to sleep, so it goes to sleep and doesn't do anything for the specified time. Even without the Sleep, it may be that the UI thread is too busy sending the email to update the display of the marquee progress bar.
You could either use a BackgroundWorker to send the email, or use the SmtpClient.SendAsync Method. The latter includes an example; there is another example at How do I send email asynchronously?.
I had the error using Excel Automation with a VB.Net application while processing and writing over 20,000 rows. I used this code to resolve the issue.
' ---- Write the Row to the Worksheet
Threading.Thread.Sleep(1000)
lstrStartingColRow = "A" & mlngIdx.ToString
If .InsertArrayIntoRow(istrWorksheetName:=lstrWorksheetName,
istrStartingCell:=lstrStartingColRow,
istrArrayOfData:=mstrExcelRow) = False Then
Throw New Exception("Insert Error *************************")
End If

VB.Net: open outlook with to,cc,subject, body , attachment

i want to open the outlook from my vb.net application. I want to fill out the To,Subject, Body and Attachment part of mail through my application. here i don't need to send mail . I want to just open the outlook with mail parameter.
Please suggest how can i achieve this task
The general procedure is as follows:
Create a mailto: link string with the required information
Pass that string to Process.Start. This will open the default mail client, not necessary Outlook.
For example, the string might look like this: mailto:mail#example.com?subject=Hello&body=test. The individual fields have to be properly escaped (URL encoded). More information about the syntax can be found in RFC 2368.
An attachment can be added by using the attachment argument in the mailto string. According to a comment on MSDN this has to be doubly quoted, though. That is:
mailto:mail#example.com?subject=Hello&body=Test&attachment=""C:\file.txt""
This task can be achieved using office interop, just add a reference to our projecto to `Microsoft.Office.Interop.Outlook'. Then in your applicattion can créate a mail and then attach files as follows:
Imports Microsoft.Office.Interop
...
Dim Outlook As Outlook.Application
Dim Mail As Outlook.MailItem
Dim Acc As Outlook.Account
Outlook = New Outlook.Application()
Mail = Outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
Mail.To = "test#test.com"
Mail.Subject = "Hello World!"
'If you have multiple accounts you could change it in sender:
For Each Acc In Outlook.Session.Accounts
'Select first pop3 for instance.
If Acc.AccountType = Microsoft.Office.Interop.Outlook.OlAccountType.olPop3 Then
Mail.Sender = Acc
End If
Next
'Take default account if no sender...
If Not Sender Is Nothing Then Mail.Sender = Sender.CurrentUser.AddressEntry
'Attach files
Mail.Attachments.Add("C:\Path\To\File.pdf")
Mail.Attachments.Add("C:\Path\To\File1.pdf")
'Append some text:
Mail.HTMLBody &= "Hello World!"
Mail.Display()
It's an old question, but I guess it could help to somebody else.
In case someone wants to do this without using outlook...
Imports System.Net.Mail
Public Function SendEmail(EmailBody As String, EmailSubject As String, EmailTo As String, AttachmentPath As String, EmailAsHTML As Boolean)
Dim Mail As New MailMessage
Try
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("[your gmail address#gmail.com]", "[the associated password]")
SMTP.Port = 587
Mail.From = New MailAddress("""[Friendly Name]"" <[your gmail address#gmail.com>")
'Split Multiple Addresses
If EmailTo.Contains(";") Then
For Each EmailAddress In EmailTo.Split(";")
Mail.To.Add(Trim(EmailAddress))
Next
Else
Mail.To.Add(Trim(EmailTo))
End If
Mail.Subject = EmailSubject
Mail.Body = EmailBody
If AttachmentPath <> "" Then Mail.Attachments.Add(New Mail.Attachment(AttachmentPath))
Mail.IsBodyHtml = EmailAsHTML
SMTP.Send(Mail)
'Clear Mail Object
Mail.Dispose()
'Function Return
Return True
Catch ex As Exception
'Function Return
Return False
End Try
End Function
Found this great post.
Programmatically adding attachments to emails in C# and VB.NET
The linked article documents how to use the MAPISendMail function provided by MAPI32.dll.
<DllImport("MAPI32.DLL")> _
Private Shared Function MAPISendMail(ByVal sess As IntPtr,
ByVal hwnd As IntPtr, ByVal message As MapiMessage,
ByVal flg As Integer, ByVal rsv As Integer) As Integer
End Function
Private Function SendMail(ByVal strSubject As String,
ByVal strBody As String, ByVal how As Integer) As Integer
Dim msg As MapiMessage = New MapiMessage()
msg.subject = strSubject
msg.noteText = strBody
msg.recips = GetRecipients(msg.recipCount)
msg.files = GetAttachments(msg.fileCount)
m_lastError = MAPISendMail(New IntPtr(0), New IntPtr(0), msg, how,
0)
If m_lastError > 1 Then
MessageBox.Show("MAPISendMail failed! " + GetLastError(),
"MAPISendMail")
End If
Cleanup(msg)
Return m_lastError
End Function
Hope it will help somebody who might find themselves way here as I did.