i'm trying to send a datagridview (or just the data in the grid) to an e-mail but i only receive a blank e-mail when it's sent, anyone got any ideas how to fix it?
The code im using is this:
Try
SMTP.UseDefaultCredentials = False
SMTP.Credentials = New Net.NetworkCredential("[e-mail address im sending from]", "[password for that e-mail]")
SMTP.Port = 25
SMTP.EnableSsl = True
mail = New MailMessage
mail.From = New MailAddress("[e-mail im sending from]")
mail.To.Add(UserEmail.Text)
mail.Body = DataTab.ToString
mail.Subject = "Biology quiz Highscores"
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network
SMTP.Send(mail)
MsgBox("E-mail sent to: " & UserEmail.Text & "")
Catch ex As Exception
MsgBox("Unable to send e-mail. Please try again later.")
End Try
im getting the data from a 2003 access database using mydataadpter sql statement, the data table variable is called datatab.
Object.ToString(), unless overridden, is identical to calling Object.GetType().ToString().
You want to show the data in the data table. You could do something like this:
Private Sub YourSubWhereYouSendEmail()
'...
Try
Using smtp = New SmtpClient() With {
.UseDefaultCredentials = False,
.Credentials = New Net.NetworkCredential("[e-mail address im sending from]", "[password for that e-mail]"),
.Port = 25,
.EnableSsl = True,
.DeliveryMethod = SmtpDeliveryMethod.Network
}
smtp.Send(New MailMessage("[e-mail im sending from]"), UserEmail.Text, "Biology quiz Highscores", DataTableToCSVString(DataTab)))
End Using
MsgBox("E-mail sent to: " & UserEmail.Text & "")
Catch ex As Exception
MsgBox("Unable to send e-mail. Please try again later.")
End Try
'...
End Sub
Private Function DataTableToCSVString(table As DataTable) As String
With New Text.StringBuilder
Dim once = False
'headers
For Each col As DataColumn In table.Columns
If once = False Then
once = True
Else
.Append(",")
End If
.Append(col.ColumnName)
Next
.AppendLine()
'rows
For Each s In table.Select.Select(Function(row) String.Join(",", row.ItemArray))
.AppendLine(s)
Next
Return .ToString
End With
End Function
Related
I was coding sender of emails in vb.net and it is giving Syntax error. Code below:
Try
Dim message As New MailMessage With {
.Subject = Me.SubjectTxt.Text
}
message.To.Add(Me.ReceiverTxt.Text)
message.From = New MailAddress(Me.EmailTxt.Text)
message.Body = Me.BodyTxt.Text
Dim num2 As Integer = (Me.AttachmentListbox.Items.Count - 1)
Dim i As Integer = 0
Do While (i <= num2)
Dim item As New Attachment(Conversions.ToString(Me.AttachmentListbox.Items.Item(i)))
message.Attachments.Add(item)
i += 1
Loop
New SmtpClient(Me.ClientBox.Text) With { _
.EnableSsl = True, _
.Credentials = New NetworkCredential(Me.EmailTxt.Text, Me.PasswordTxt.Text), _
.Port = Conversions.ToInteger(Me.PortTxt.Text) _
}.Send(message)
Interaction.MsgBox(("Message sent to " & Me.ReceiverTxt.Text), MsgBoxStyle.Information, "SMTP Email Sender")
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim exception As Exception = exception1
If (Me.ReceiverTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Receiver.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.SubjectTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up Subject.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.BodyTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Message Body.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.EmailTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Email for Account Log In.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.PasswordTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Password for Account Log In.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.ClientBox.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Server for basis of SMTP Server.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.PortTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Port to successfully send the email.", MsgBoxStyle.Exclamation, "You missed something!")
Else
Interaction.MsgBox("Sending Failed", DirectCast(Conversions.ToInteger("SMTP Email Sender"), MsgBoxStyle), Nothing)
End If
ProjectData.ClearProjectError()
End Try
The error is in New SmtpClient
Problem of initializers - you don't know which line is a problem. First, break your code into many lines.
Dim smtp As New SmtpClient(Me.ClientBox.Text) With { .EnableSsl = True }
smtp.Credentials = New NetworkCredential(Me.EmailTxt.Text, Me.PasswordTxt.Text)
smtp.Port = Conversions.ToInteger(Me.PortTxt.Text)
smtp.Send(message)
Generally, your problem was in line starting with new. I just tested it, it doesn't work in vb. Something like this - (new class()).DoSomething works in c#. But not in vb. But then again, complex initializers can be detrimental in debugging issues. Now you will be able which line exactly causes the error.
Also, you should add .Trim() everywhere
Me.PortTxt.Text.Trim()
This should have worked:
With New SmtpClient(Me.ClientBox.Text.Trim) With {
.EnableSsl = True,
.Credentials = New NetworkCredential(Me.EmailTxt.Text.Trim, Me.PasswordTxt.Text.Trim),
.Port = Conversions.ToInteger(Me.PortTxt.Text.Trim) }
.Send(message)
End With
Note that the .Send is against the outer With block, and the underscores aren't needed. Also added .Trim as the other answer suggested.
I'm adding an email sender in my app, so i used this:
Try
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
oMail.From = "app-NHK#hotmail.com" ' From
oMail.To = "NHKomaiha#hotmail.com" ' To
oMail.Subject = Title.Text 'Title
oMail.TextBody = MsgTxt.Text 'Body
Dim oServer As New SmtpServer("smtp.live.com") ' SMTP server address
oServer.User = "app-NHK#hotmail.com" 'here i have written my app's email address made for sending the email from this form
oServer.Password = "thepassword" 'here i have put my app email password
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto ' if SSL connection required
UseWaitCursor = True
Here done setting the main needed info
oSmtp.SendMail(oServer, oMail)
Sending...
UseWaitCursor = False
MessageBox.Show("E-Mail Sent Successfully", "Contact by E-Mail", MessageBoxButtons.OK, MessageBoxIcon.Information)
Main.BringToFront()
Main.Enabled = True
Close()
Error catching...
Catch ep As Exception
UseWaitCursor = False
MessageBox.Show("Error while sending E-Mail." & vbCrLf & vbCrLf & ep.Message, "Contact by E-Mail", MessageBoxButtons.OK, MessageBoxIcon.Error)
Dim closeerror = MessageBox.Show("Do you want to close?", "Contact by E-Mail", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If closeerror = DialogResult.Yes Then
Main.BringToFront()
Main.Enabled = True
Close()
End If
End Try
Is this code wrong? i used a lot of ways to send email but none worked
This time i got error: 550 5.3.4 Requested action not taken; To continue sending messages, please sign in to your account.
Modify and try this working example:
Imports System.Net.Mail
...
Try
Dim Email As New MailMessage()
Email.From = New MailAddress("abcdef#gmail.com")
Email.To.Add("other#provider.com")
Email.Subject = "Subject"
Email.IsBodyHtml = False 'or true if you want html
Email.Body = TextBox1.Text
Dim EmailClient As New SmtpClient("smtp.gmail.com", 587)
EmailClient.EnableSsl = True
EmailClient.Credentials = New Net.NetworkCredential("abcdef#gmail.com", "password")
EmailClient.Timeout = 7000
EmailClient.Send(Email)
Catch ex As SmtpException
MsgBox(ex.StatusCode & vbCrLf & ex.Message, vbCritical, "SMTP Error!")
End Try
Usually you need to specify port and authentication type in order to connect to an smtp server. It seems that smtp.live.com use SSL and port 465 (please verify this data).
So you can use SmtpClient.Port property to sets the port used for SMTP transactions and SmtpClient.EnableSSL to specify that SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.
I am trying to make a ConsoleApplication attach all files in a folder to an email and send it. I know how to do it with a single attachment, but for the life of me, I cannot figure out how to attach all items in a folder.
Current code:
Sub Main()
Try
Dim mail As New MailMessage("from", "to")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
Dim file As System.Net.Mail.Attachment
file = New System.Net.Mail.Attachment("Path to single file")
mail.Attachments.Add(file)
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
Thanks in advance
EDIT:
I tried the below code that I found on another post, but it just errors out (and using the ConsoleApplication, I am not sure how to view the exact error its giving)
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
I got it working!
Sub Main()
Try
Dim mail As New MailMessage("from", "too")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
I have this code:
For i = 0 To DataGridView1.RowCount - 2
If send_email(body, DataGridView1.Rows(i).Cells(8).Value.ToString) Then
countSentMail = countSentMail + 1
System.Threading.Thread.Sleep(2 * 1000)
ProgressBar1.PerformStep()
End If
Next i
Private Function send_email(ByVal body As String, ByVal emailAddress As String) As Boolean
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Port = [port]
SmtpServer.Host = [ip]
mail = New MailMessage()
mail.From = New MailAddress([email_from])
mail.To.Add([email_to])
mail.Bcc.Add([email_bbc])
mail.Subject = [subject]
mail.Body = body
Mail.IsBodyHtml = True
SmtpServer.Send(mail)
send_email = True
Catch ex As Exception
send_email = False
End Try
End Function
And when code runs form/application gets "not responding" till sends out all email and progress bar becomes useless. If I comment out content of sending function - progress bar works as I expect. Any suggestions?
Sorry for the delay on reply.
Yes. You are invoking send_email before increasing ProgressBar1
send_email uses SmtpClient.Send() which is synchronous and waits for a server response.
You can use SmtpClient.SendAsync() instead, which will continue the execution and waits the server response on background.
I'm sending emails through VB.NET like in showed code:
Dim retval As Integer
Dim attachment As System.Net.Mail.Attachment = Nothing
If fileName <> "" Then
attachment = New System.Net.Mail.Attachment(fileName)
End If
Dim client As New SmtpClient()
With client
.EnableSsl = True
.Host = smtpServerAddress
.Port = 587
.DeliveryMethod = SmtpDeliveryMethod.Network
.UseDefaultCredentials = False
.Credentials = New NetworkCredential(FromEmailId, password)
AddHandler .SendCompleted, AddressOf SendCompletedCallback
End With
Dim mail = New MailMessage(FromEmailId, toEmailId)
With mail
.Priority = MailPriority.High
.Subject = subject
.SubjectEncoding = System.Text.Encoding.UTF8
.IsBodyHtml = False
If fileName <> "" Then
.Attachments.Add(attachment)
End If
.Body = msgBody
.BodyEncoding = System.Text.Encoding.UTF8
End With
Try
client.SendAsync(mail, "")
retval = 1
Catch ex As Exception
retval = 0
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return retval
This work's well.
Problem is only that my Try/Catch block dont react as expected if I'm not connected to internet. The only way I can know that mail didn't go out is that I don't receive message from callback what can take a long time. Also, I get returned 1 from function like email is sended properly.
Which is usual way to check if internet connection exists and if mail is start to be sended?
If you want to catch all exception thrown from SmtpClient you could send mail synchronously. If you prefer asynchronous way, use SendMailAsync which returns Task instance on which you can call ContinueWith to set error handler:
client.SendMailAsync(mail).ContinueWith(t=>HandleError(t.Exception), TaskContinuationOptions.OnlyOnFaulted)