'Variable which will send the mail
Dim obj As System.Net.Mail.SmtpClient
'Variable to store the attachments
Dim Attachment As System.Net.Mail.Attachment
'Variable to create the message to send
Dim Mailmsg As New Mail.MailMessage()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim ol As New Outlook.Application()
Dim ns As Outlook.NameSpace
Dim fdMail As Outlook.MAPIFolder
ns = ol.GetNamespace("MAPI")
ns.Logon(, , True, True)
'creating a new MailItem object
Dim newMail As Outlook.MailItem
'gets defaultfolder for my Outlook Outbox
fdMail = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox)
'assign values to the newMail MailItem
newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
newMail.Subject = "tesst"
newMail.Body = "test"
newMail.To = TextBox1.Text
Dim sSource As String = Application.StartupPath + "\kk.sys"
' TODO: Replace with attachment name
Dim sDisplayName As String = "kaar.jpg"
Dim sBodyLen As String = newMail.Body.Length
newMail.SaveSentMessageFolder = fdMail
newMail.Send()
Catch ex As Exception
Using writer As StreamWriter = New StreamWriter(Application.StartupPath + "\err1.txt")
writer.WriteLine(ex.ToString)
End Using
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
Dim address As New MailAddress(TextBox1.Text, "Nigraan")
Dim oAttch As Mail.Attachment = New Mail.Attachment(Application.StartupPath + "\kk.sys")
SmtpServer.Credentials = New _
Net.NetworkCredential(TextBox2.Text, TextBox3.Text)
SmtpServer.Port = "587"
SmtpServer.Host = "smtp.gmail.com"
mail = New MailMessage()
mail.From = New MailAddress(TextBox2.Text)
mail.To.Add(New MailAddress(TextBox1.Text))
mail.Subject = TextBox3.Text
mail.Body = "test"
mail.Attachments.Add(oAttch)
SmtpServer.Send(mail)
Catch ex As Exception
Using writer As StreamWriter = New StreamWriter(Application.StartupPath + "\err2.txt")
writer.WriteLine(ex.ToString)
End Using
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Try
System.Diagnostics.Process.Start("mailto:" & TextBox1.Text & "?subject=" & "re:Subject" & "&body=" & "EmailBody")
Catch ex As Exception
Using writer As StreamWriter = New StreamWriter(Application.StartupPath + "\err3.txt")
writer.WriteLine(ex.ToString)
End Using
End Try
End Sub`
errors are:
err1:
System.Runtime.InteropServices.COMException (0x80004005): There must be at least one name or distribution list in the To, Cc, or Bcc box.
at Microsoft.Office.Interop.Outlook._MailItem.Send()
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e)
err2:
System.ArgumentException: The parameter 'address' cannot be an empty string.
Parameter name: address
at System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding)
at WindowsApplication1.Form1.Button2_Click(Object sender, EventArgs e)
When i send using a machine with visual studio both mail gets sent, when not these errors show.
i have double checked .net framework
thank you..
Try creating a variable string and set that before sending the mail
Dim ToEmail as string
ToEmail = Textbox1.text
Then set your to address first.
'assign values to the newMail MailItem
newMail.To = ToEmail
newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
newMail.Subject = "tesst"
newMail.Body = "test"
i got everything working,
got smtp to work by giving ssl encryption to true
got outlook to work by creating a contact and giving the contact's email id in the 'to' field
just don't save the contact if u don't want the contact to be added in outlook :D
yeyyy!!
Related
I know this is an old issue or concern but can you help me on this.
I have a source code found in the internet that can send an attachment via email. I tried it in my application but I getting this error.
System.Web.HttpException (0x8000405) Invalid mail attachment C:\File.pdf
at System.Web.Mail.MailAttachment.VerifyFile()
at System.Web.Mail.Attachment..ctor(String filename)
This is the code I found
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Web.Mail
Public Class ReportsForm
Dim cryRpt As New ReportDocument
Dim pdfFile As String = "C:\File.pdf"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cryRpt.Load("Crystal Report Path here")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions
CrDiskFileDestinationOptions.DiskFileName = pdfFile
CrExportOptions = cryRpt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.PortableDocFormat
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
cryRpt.Export()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
sendMail()
End Sub
Private Sub sendMail()
Try
Dim Smtp As SmtpMail
SmtpMail.SmtpServer.Insert(0, "hostname")
Dim Msg As MailMessage = New MailMessage
Msg.To = "to address"
Msg.From = "from address"
Msg.Subject = "Crystal Report Attachment "
Msg.Body = "Crystal Report Attachment "
Msg.Attachments.Add(New MailAttachment(pdfFile))
SmtpMail.Send(Msg)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Thank you
I think the problem is your pdf attachment file. You are going to need somewhere safe to create it. You'll create the attachment file path and name using this code:
Dim pdfFile As String = System.IO.Path.GetTempPath & "File.pdf"
If System.IO.File.Exists(pdfFile) Then My.Computer.FileSystem.DeleteFile(pdfFile)
Then you'll export the cryRpt object to a pdf file using just one line of code:
cryRpt.ExportToDisk(ExportFormatType.PortableDocFormat, pdfFile)
If no exception occurs your attachment is created and ready to be mailed.
Imports System.Net.Mail
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient(My.Settings.smtpserver)
mail.From = New MailAddress(My.Settings.from)
mail.[To].Add(My.Settings.destination)
mail.Subject = "Program"
mail.Body = "Hi this is a msg form .net application"
Dim path As String = My.Settings.desktop
Dim dir As New DirectoryInfo(path)
Dim filesInDirectory As FileInfo() = dir.GetFiles()
Dim attach As System.Net.Mail.Attachment
For Each file In filesInDirectory
attach = New System.Net.Mail.Attachment(file.FullName)
mail.Attachments.Add(attach)
Next
SmtpServer.Port = My.Settings.port
SmtpServer.Credentials = New
System.Net.NetworkCredential(My.Settings.username, My.Settings.password)
SmtpServer.EnableSsl = True
SmtpServer.Send(mail)
MsgBox("Sent Successfuly!", MsgBoxStyle.Information, "Send!")
mail.CC.Add(My.Settings.CC)
mail.Bcc.Add(My.Settings.BCC)
Catch ex As Exception
MsgBox("Failed Sending Email!", MsgBoxStyle.Critical, "Failed!")
End Try
Application.Exit()
End Sub
End Class
the cc and bcc is not working i cant send through cc nor bcc is there any problem with my codes? the user can use this cc and bcc like gmail.
Well - you are setting CC and BCC after you send the email. Thats your problem. Move the lines:
mail.CC.Add(My.Settings.CC)
mail.Bcc.Add(My.Settings.BCC)
Up to where you are setting Mail.Subject, etc.
I really started to get confused about sending an e-mail to (example: test#test.com) through VB.NET and for sure using SMTP.
I want the mail to be sent when Button1 is clicked (example).
So I started by a code like that
Imports System.Net.Mail
Public Class MyProgram
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using message As New MailMessage()
'set to the from, to and subject fields
message.From = New MailAddress("sender#sender.com")
message.[To].Add(New MailAddress("test#test.com"))
message.Subject = "Test"
'code the message body
Dim MsgBody As String
MsgBody = TextBox1.Text.ToString() & vbCr & _
TextBox2.Text.ToString()
message.Body = MsgBody
Dim client As New SmtpClient()
client.Host = "smtp.example.com"
client.Port = "465"
client.EnableSsl = True
client.Credentials = New Net.NetworkCredential("USERNAME#MAIL.COM", "PASSWORD")
client.Send(message)
End Using
'display submitted box
MessageBox.Show("Congrats", "Congratulations!")
'close form
Me.Close()
End Sub
End Class
And I get:
Next, I tried another code (which is) ...
Imports System.Net.Mail
Public Class MyProgram
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("USERNAME#MAIL.COM", "PASSWORD")
Smtp_Server.Port = 465
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.example.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("sender#sender.com")
e_mail.To.Add("test#test.com")
e_mail.Subject = "Test E-mail Address Sent by My Program"
e_mail.IsBodyHtml = False
e_mail.Body = "Test"
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
End Sub
End Class
And now I get the following in the Debugger:
And at last the e-mail isn't sent!
Please don't say "sender#sender.com" isn't configured as a sender e-mail address because it is!
I really need help!
Thanks. :-)
Can anyone help me. I've created a email program. I'm having an error when clicking on the send button. Here's my code:
Imports System.Net.Mail
Public Class frmEmail
Dim emailaddress As String
Dim password As String
Dim port As Integer
Dim host As String
Private Sub frmEmail_Load(sender As Object, e As EventArgs)
If emailaddress.ToLower.Contains("#gmail") Then
port = 587
host = "smtp.gmail.com"
ElseIf emailaddress.ToLower.Contains("#yahoo") Then
port = 465
host = "smtp.mail.yahoo.com"
End If
End Sub
Private Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSend.Click
Try
Dim smtpServer As New SmtpClient
Dim mail As New MailMessage()
smtpServer.Credentials = New Net.NetworkCredential(emailaddress, password)
smtpServer.Port = port
smtpServer.Host = host
smtpServer.EnableSsl = True
mail = New MailMessage()
mail.From = New MailAddress(emailaddress)
mail.To.Add(txtTo.Text)
mail.Subject = txtSubject.Text
mail.Body = txtMessage.Text
smtpServer.Send(mail)
MsgBox("The mail is send!", MsgBoxStyle.Information)
Catch error_t As Exception
MsgBox(error_t.ToString)
End Try
End Sub
End Class
And I've got this error: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name:value
at System.Net.Mail.SmtpClient.set_Port(Int32 value)
***Edited forgot to modify it to the original code
Your sub
Private Sub frmEmail_Load(sender As Object, e As EventArgs)
doesnt run when the form loads.
Because of this port is set to the default value of 0
You need to tell VB.Net to run when the form loads like this
Private Sub frmEmail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Also further on down the code, you might find that you get an error about authentication from the email server. If you get this, just below
Dim smtpServer As New SmtpClient
add this
smtpServer.UseDefaultCredentials = False
it might work.
I have a sendmail program in vb.net. I have attachments sending just fine. The problem is when there is NO ATTACHMENT, the program errors out. How do i handle no attachment to bypass and send with no attachment? The below works fine.
Yea yea i know, my naming convention is horrible. I will change once i have the logic 100% complete.
Imports System.Net.Mail
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
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("emtnap6#yahoo.com")
Dim FromEmailAddress As String = Recipients(0)
Dim Subject As String = "IT Help!"
Dim Body As String = TextBox1.Text
Dim UserName As String = "fakeout"
Dim Password As String = "fakeout"
Dim Port As Integer = 587
Dim Server As String = "smtp.gmail.com"
Dim Attachments As New List(Of String)
MsgBox(SendEmail(Recipients, FromEmailAddress, Subject, Body, UserName, Password, Server, Port, Attachments))
TextBox2.Text = "Attach Screenshot:"
TextBox2.TextAlign = HorizontalAlignment.Right
lblpleasewait.Visible = False
TextBox1.Text = ""
TextBox1.Focus()
End If
End Sub
Sub delay(ByVal delay_ms As Integer)
Dim tspan As New TimeSpan
Dim tstart = Now
While tspan.TotalMilliseconds < delay_ms
tspan = Now - tstart
Application.DoEvents()
End While
End Sub
Function SendEmail(ByVal Recipients As List(Of String), _
ByVal FromAddress As String, _
ByVal Subject As String, _
ByVal Body As String, _
ByVal UserName As String, _
ByVal Password As String, _
Optional ByVal Server As String = "smtp.gmail.com", _
Optional ByVal Port As Integer = 587, _
Optional ByVal Attachments As List(Of String) = Nothing) As String
Dim Email As New MailMessage()
Try
Dim SMTPServer As New SmtpClient
''For Each Attachment As String In Attachments
'' Email.Attachments.Add(New Attachment(Attachment))
'Next
Dim mailattach As String = TextBox2.Text
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(mailattach)
Email.Attachments.Add(attachment)
Email.From = New MailAddress(FromAddress)
For Each Recipient As String In Recipients
Email.Bcc.Add(Recipient)
Next
Email.Subject = Subject
Email.Body = Body
SMTPServer.Host = Server
SMTPServer.Port = Port
SMTPServer.Credentials = New System.Net.NetworkCredential(UserName, Password)
SMTPServer.EnableSsl = True
SMTPServer.Send(Email)
Email.Dispose()
Return "Email to Derek was successfully sent."
Catch ex As SmtpException
Email.Dispose()
Return "Sending Email Failed. Smtp Error."
Catch ex As ArgumentOutOfRangeException
Email.Dispose()
Return "Sending Email Failed. Check Port Number."
Catch Ex As InvalidOperationException
Email.Dispose()
Return "Sending Email Failed. Check Port Number."
End Try
End Function
Private Sub FolderBrowserDialog1_HelpRequest(sender As Object, e As EventArgs)
If (FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
TextBox2.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
TextBox2.Text = OpenFileDialog1.FileName
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Focus()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If Not Environment.Is64BitProcess Then
Process.Start("C:\Windows\sysnative\SnippingTool.exe")
Else
Process.Start("C:\Windows\system32\SnippingTool.exe")
End If
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
OpenFileDialog1.InitialDirectory = Environment.SpecialFolder.MyComputer
End Sub
End Class
This should solve the problem.
If TextBox2.text <> "" then
Dim mailattach As String = TextBox2.Text
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(mailattach)
Email.Attachments.Add(attachment)
End if