Using Sleep in VB.NET - 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

Related

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

Receiving "Run-time error '2293': Microsoft Access can't send this e-mail message" after having no issues

I have a button on an Access form that queues up an email and is linked to several fields on the form. Yesterday and this morning the button was working without issue. I have not changed the underlying code or any of the fields in the form, but suddenly the button is returning a Run-time error '2293': Microsoft Access can't send this e-mail message error message when I click it. An example of the code is as follows:
Private Sub cmd_Button_Click()
Dim toaddress As String
Dim ccaddress As String
Dim subject As String
Dim message As String
toaddress = AddMailAddress(toaddress, Nz(Me.cmb_ProjectLead.Column(1), ""))
toaddress = AddMailAddress(toaddress, Nz(Me.cmb_ProjectLead2.Column(1), ""))
ccaddress = AddMailAddress(ccaddress, Nz(Me.cmb_OtherPOC.Column(1), ""))
ccaddress = AddMailAddress(ccaddress, Nz(Me.cmb_OtherPOC2.Column(1), ""))
subject = "text" & me.txb_ProjectName
message = "text" & me.txb_ProjectName & vbnewline & me.txb_ProjectLocation & vbnewline & me.txb_ProjectDescription
DoCmd.SendObject acSendNoObject, , , toaddress, ccaddress, , subject, message, True
End Sub
When I click "debug" on the error message, the line DoCmd.SendObject acSendNoObject, , , toaddress, ccaddress, , subject, message, True is highlighted yellow with a yellow arrow pointed to it.
A few notes that may be helpful:
I'm working on a work issued computer and I have no Admin rights, so changing certain properties are not possible.
I have to use a VPN which has pretty strict security standards.
To reiterate, this worked up until today. In fact for the same record, it worked one moment, and then 30 seconds later did not work.
*Update: the command worked when I stripped everything except the sendobject line and replaced the values with text, i.e.
Private Sub cmd_Button_Click()
DoCmd.SendObject acSendNoObject, , , "toaddress", "ccaddress", , "subject", "message", True
End Sub
When I added just the toaddress and ccaddress back in, I got the 2293 error message.
*Additional info that may help: This form has several "Email To" buttons as well as some "Send Outlook Apppointment To" buttons. They all also worked fine up until this morning, but are now generating various error messages when clicked. They all use the same toaddress, ccaddress, subject, message, etc format as my example here.
The public function that is also linked to these commands is as follows:
Public Function AddMailAddress(address As String, newaddress As String)
If (address = "") And (newaddress = "") Then
Exit Function
End If
If address = "" Then
address = newaddress
Else
If Not newaddress = "" Then
If VBA.Right(address, 1) = ";" Then
address = address & newaddress
Else
address = address & ";" & newaddress
End If
End If
End If
AddMailAddress = address
End Function
Anytime i get this error, it has nothing to do with the the database or the code, it is simply due to the fact that i have an outlook item open that is currently gettin edited that i have forgotten about.
Access cannot create a new Outlook item while there is currently an Outlook item open in edit mode.
Close down any Outlook items open in edit mode and try again.
The email buttons now work after closing out the database and re-opening it. Still no clue why it gave me run-time errors before. If it happens again, I'll be back to add more insight.

How to send an email with attachment using default email client in vb.net

I am wondering if how it could be done. Is it possible to do it?
Here is my simple code:
Try
MsgBox("Please wait this may takes time to load", vbInformation, "Mailing System")
System.Diagnostics.Process.Start("mailto:" & txtEmailadd.Text)
Catch ex As Exception
MsgBox(ex.Message & " Having some technical difficulties, kindly check if the email textbox has data in it", vbCritical, "System Advisory")
End Try
I want to add an attachment inside of this before the default client loads. Unfortunately, i don't find any answers in the web. Can you give some advice? Thanks so much in advance.
you need to call the MailMessage.Attachments(). Here's the example code:
Dim MailMsg as New MailMessage
Dim loAttachment As Attachment = Nothing
Dim ls_email_attach as String
Dim server as String
ls_email_attach = "attach.xls"
server = "Mail server info"
//add the attachment
If Not ls_email_attach.Trim = "" Then
loAttachment = New Attachment(ls_email_attach)
loMailMsg.Attachments.Add(loAttachment)
End If
//send the email
MailMsg = New SmtpClient(server)
MailMsg.Send(loMailMsg)
Please see this for reference.
Hope it helps

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.

VB script and chrome

I'm having a lot of trouble modifying an existing website written in VB.NET.
Can someone please explain to me the basics to of the VB.NET-chrome relationship?
The specific problem I have is with sending mail through the website, I have no problem to add the relevant code, I just feel like I need to understand more before I start looking for bugs.
In the website there's an option to send an e-mail to a list of people. This option works in IE but doesn't work in firefox and chrome. I basically have a form tag which holds a table with a list of people with a check button next to every name. When you click send there's a function defined like this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sTo As String, sFrom As String, sSubject As String, sBody As String
Dim sCc As String, sBcc As String
Dim MyMail As MailMessage = New MailMessage
sFrom = "Laboratory Mail system sent from " & Session.Contents("UserNameEng") & " <dbsystem#mscc.huji.ac.il>"
sTo = Trim(Request.Form("EmailTo")) & txtTo.Text
sCc = Trim(Request.Form("EmailCc")) & txtCc.Text
sSubject = Trim(txtSubject.Text)
sBody = Trim(txtBody.Text)
sBody = sBody.Replace(vbCrLf, "<br />") 'new
MyMail.Headers.Add("Reply-To", Session.Contents("UserEmail"))
MyMail.From = sFrom
MyMail.To = sTo
MyMail.Subject = sSubject
MyMail.BodyFormat = MailFormat.Html 'new
'MyMail.Body = sBody
Select Case optDirection.SelectedValue.ToString
Case "BodyRtl"
MyMail.Body = "<style> body {direction: rtl} </style>" & sBody
Case "BodyLtr"
MyMail.Body = "<style> body {direction: ltr} </style>" & sBody
End Select
' MyMail.Body = "<style> body {direction: rtl} </style>" & sBody 'new
' MyMail.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-8-i")
MyMail.Cc = sCc
If chkCopyForMe.Checked Then
MyMail.Bcc = Session.Contents("UserEmail")
End If
'MyMail.BodyFormat = MailFormat.Text
Select Case optPriority.SelectedValue.ToString
Case "Normal"
MyMail.Priority = MailPriority.Normal
Case "High"
MyMail.Priority = MailPriority.High
Case "Low"
MyMail.Priority = MailPriority.Low
End Select
If Trim(UploadFile.Value) <> vbNullString Then
Dim myAttachment As New MailAttachment(GetAttachment(Trim(UploadFile.Value))) '(Trim(UploadFile.Value))
MyMail.Attachments.Add(myAttachment)
End If
SmtpMail.SmtpServer = "pluto.mscc.huji.ac.il"
Try
SmtpMail.Send(MyMail)
Response.Redirect("SentMessage.aspx?m=1")
Catch ex As Exception
lblComment.Text = "Problem With Sending Mail<br />" & ex.Message
'Response.Redirect("SentMessage.aspx?m=2")
End Try
End Sub
which is suppose to send the mail to the selected boxes. In IE the mail arrives, in chrome it doesn't.
VB.NET is a server side technology - it outputs HTML to the browser.
The browser interacts with this HTML and may send responses to the server (clicking links, posting forms and such) - the VB.NET code can interpret these and respond with HTML.
This works the same way regardless of what browser (Chrome, IE, Firefox, Opera or any other).
This code has nothing to do with your problem. The browser never sees it, only the server.
You've made a mistake somewhere in your .aspx file: IE is guessing correctly what you really want, and Chrome is not.
What happens with Firefox?