VB.Net Email not putting copy in sent folder - vb.net

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")

Related

File Being Used By .NET Mail

I wrote a simple program written to collect files, send the files, then delete said files. I am sending them via Email using System.Net.Mail
If Label6.Text = "" Then
mail.Attachments.Add(New Attachment(zipPath))
End If
'Enables SSL, if required
ssl = Provider.ssl
If skipAhead = True Then
ssl = True
End If
If ssl = True Then
SmtpServer.EnableSsl = True
End If
'Sends the email
SmtpServer.Send(mail)
'Allows the user to either keep testing, or quit.
If skipAhead = True Then
My.Computer.FileSystem.DeleteFile(unalteredPath)
My.Computer.FileSystem.DeleteFile(unalteredPath1)
My.Computer.FileSystem.DeleteFile(zipPath)
Else
Dim keepOpen As Integer = MsgBox("The Email was sent. You can keep testing if you would like to. Press ok to close, and cancel to keep testing", MsgBoxStyle.OkCancel)
If keepOpen = 1 Then
Close()
End If
End If
As seen in line 2, the attachment is added to the email, and I do not attempt to delete the attachment until after the email is sent, however when the code is running, it throws an error that the file is being used by another process.
I am also wondering if this could be lingering from the .zip being created itself. Here is the code that does that:
Public Sub Zipping()
'Copies files to the folder where they will be zipped from
My.Computer.FileSystem.CopyFile(unalteredPath, outputs & "\ExIpOutput.txt")
My.Computer.FileSystem.CopyFile(unalteredPath1, outputs & "\IpConfig.txt")
'Deletes the old output files
My.Computer.FileSystem.DeleteFile(unalteredPath)
My.Computer.FileSystem.DeleteFile(unalteredPath1)
'Starts the zip Sub
ZipFile.CreateFromDirectory(outputs, zipPath, CompressionLevel.Fastest, True)
My.Computer.FileSystem.DeleteDirectory(outputs, FileIO.DeleteDirectoryOption.DeleteAllContents)
End Sub
Here is the CreateFromDirectory sub:
Public Shared Sub CreateFromDirectory(sourceDirectoryName As String, destinationArchiveFileName As String, compressionLevel As Compression.CompressionLevel, includeBaseDirectory As Boolean)
End Sub
Is there something I'm missing here, or do I need to have the program sleep for a bit to let the email send, then delete the .zip file?
You can load the file into an array: File.ReadAllBytes(String) Method.
Then get a MemoryStream from that: How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?
And finally, you can use a MemoryStream for an attachment: Attach a file from MemoryStream to a MailMessage in C#.
As the data to be sent is in memory, you should be able to delete the file. Note that if there is a crash, the data is gone.
The examples are in C#, but if you have problems using the methods in VB.NET, please edit your question to show how far you've got and tell us what the problem is.
A better solution to this issue is to dispose the Attachment object that is locking the file. Any object you create that has a Dispose method should have that method called when you're done with the object and an Attachment is no different.
Dim fileAttachment As Attachment
If Label6.Text = "" Then
fileAttachment = New Attachment(zipPath)
mail.Attachments.Add(fileAttachment)
End If
'...
SmtpServer.Send(mail)
If fileAttachment IsNot Nothing Then
fileAttachment.Dispose()
End If

Sending Mail with headers and saved in user's Sent Items 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).

SMTP outgoing server does not send text inside the email by vb.net

I developed apart of an application that sends emails to partners and clients with a saved email subject and text; so i used the vb.net settings to declare variables to be initiated with the program. and then asked the user to save his email subject and body to be used again later.
the problem is when i attemped to send the email, the email reaches the otherside yet with no content at all ( mail subject and body are null).
some points may be taken into consideration:
i used background worker (thread dirrent than the UI thread)
the outgoing mail is SMTP (Gmail server).
I passes the Body and the subject as strings to the sub sendmail().
Is there any better method to store mail's body and subject instead of string variables ?
I am sure that the SMTP took all my strings
Sub sendmail(receiver As String, mailsubject As String, mailbody As String, mailattachement As String)
Dim email As New System.Net.Mail.MailMessage
Dim smtp As New System.Net.Mail.SmtpClient
Try
With smtp
.EnableSsl = My.Settings.mailssl
.Port = My.Settings.mailport
.Host = My.Settings.mailhost
.Credentials = New Net.NetworkCredential(My.Settings.mailaddress, My.Settings.mailpassword)
End With
With email
.From = New System.Net.Mail.MailAddress(My.Settings.mailaddress)
.Subject = severalclientmailsubject
.Body = severalclientmailbody
.To.Add(receiver)
End With
smtp.Send(email)
Catch ex As Exception
'Generic Exception raised.
changestatus2("General Error.")
End Try
End Sub
what could can cause this thing ?!?

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