vb.net send email with image - vb.net

there is a lot of topic about sending email with attachment but i couldn't find what i was looking for
my form contain 8 textbox and 1 PictureBox i can send all textbox via email but ican't send PictureBox i try many code
this is my form.
and here is my code
Dim MyMessage As New MailMessage
Try
MyMessage.From = New MailAddress("x#gmail.com")
MyMessage.To.Add("x#gmail.com")
MyMessage.Subject = "Data"
MyMessage.Body = Label1.Text + " = " + IDTextBox.Text + Environment.NewLine + Label2.Text + " = " + ناوی_سیانی_کارمەندTextBox.Text + Environment.NewLine + Label3.Text + " = " + ساڵی_لە__دایک_بوونTextBox.Text + Environment.NewLine + Label4.Text + " = " + شوێنی_دانیشتنTextBox.Text + Environment.NewLine + Label5.Text + " = " + گروپی_خوێنTextBox.Text + Environment.NewLine + Label6.Text + " = " + ناو_نیشانی_کار_لە_کۆمپانیاTextBox.Text + Environment.NewLine + Label7.Text + " = " + ژمارەی_مۆبایلTextBox.Text + Environment.NewLine + Label8.Text + " = " + شوێنی_کارTextBox.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("x#gmail.com", "x")
SMTP.Send(MyMessage)
MsgBox("your message Has been sent successfully")
Catch ex As Exception
End Try
i will be greatfull if you could help me :)

Have you tried this.You can use the LinkedResource and AlternatiView for the same.
string path = Filelocation; // as you are using picture box,give the location from where the image is loading into picture box.
LinkedResource imageLink = new LinkedResource(path);
imageLink.ContentId = "myImage";
AlternateView altView = AlternateView.CreateAlternateViewFromString(
"<html><body><img src=cid:myImage/>" +
"<br></body></html>" + strMailContent,
null, MediaTypeNames.Text.Html);
altView.LinkedResources.Add(imageLink);
//now append it to the body of the mail
msg.AlternateViews.Add(altView);
msg.IsBodyHtml = true;
or
You can send it with HtmlBody here is the
reference : http://vba-useful.blogspot.fr/2014/01/send-html-email-with-embedded-images.html

You need to add the directory of the picture file or any file you have and add it as attachment to your mail like this...
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(FilePath)
MyMessage.Attachments.Add(attachment)

Related

Mail sending fail with attachment on IIS 7.5 with MVC 4

I am trying to send mail with attachment through hosted website on IIS7.5.
I am able to send mail without attachment but not with attachment.
I have developed web site in Asp.Net MVC4.
I am able to send mail through IIS7.5 which installed on my local machine.
MemoryStream objMemoryStream = new MemoryStream();
StringReader sr = new StringReader(RazorViewToString.RenderRazorViewToString(this, "~/Views/Booking/BookingFormPdf.cshtml", objBookingForm));
Document pdfDoc = new Document(PageSize.A3, 20f, 20f, 20f, 20f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, objMemoryStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
byte[] Attachment = objMemoryStream.ToArray();
string Subject = objBookingForm.modBookingDetail.CompanyName + " Confirmation of Advertising Booking " + BookingId + ".";
string Body = "Dear " + objBookingForm.modBookingDetail.CustomerContact + "," + Environment.NewLine + Environment.NewLine + "We are pleased to confirm your advertising booking with " + objBookingForm.modBookingDetail.CompanyName + Environment.NewLine + Environment.NewLine + "Please find attached a pdf copy for your records." + Environment.NewLine + Environment.NewLine + "Regards" + Environment.NewLine + Environment.NewLine + objBookingForm.modBookingDetail.BookedBy + Environment.NewLine + objBookingForm.modBookingDetail.CompanyName;
SendEmail(objBookingForm.modBookingDetail.CustomerEmailId, Subject, Body, Attachment);

calling HTTP web page in vb.net

i have this code in my vb.net application:
myHttpWebRequest = WebRequest.Create(url)
myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
If myHttpWebResponse.StatusCode = HttpStatusCode.OK Then
receivestream = myHttpWebResponse.GetResponseStream()
encode = System.Text.Encoding.GetEncoding("utf-8")
Dim readStream As New StreamReader(receivestream, encode)
response = readStream.ReadToEnd()
myHttpWebResponse.Close()
receivestream.Close()
readStream.Close()
TextBox1.Text = TextBox1.Text + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + vbCrLf + "URL: " + url + vbCrLf + vbCrLf
'scroll to bottom
TextBox1.SelectionStart = TextBox1.Text.Length
TextBox1.ScrollToCaret()
Me.Refresh()
Else
TextBox1.Text = TextBox1.Text + "Could not contact server for: " + url + vbCrLf + vbCrLf
'scroll to bottom
TextBox1.SelectionStart = TextBox1.Text.Length
TextBox1.ScrollToCaret()
Me.Refresh()
End If
sometimes i get 500 internal server errors or 404 not found
also if the internet connection goes down that this program is running on i get an error too
the above code is inside a loop. how can i just skip this loop if there is an error
Use a try catch outside your loop, and log your errors. You can exit a for loop with a simple Exit keyword. Also you can refactor your code into a single method and just exit that as well.

Visual Basic - Cannot access file because used by another process even after closed file

My script automatically uploads a text file after being created and editted through the program. The creating and editting (appending) works fine, but when the exe reaches the line where the file is uploaded, I get the error:
Cannot access file because used by another process
The file is being closed and disposed before uploading, but that doesn't matter. Even after some google searches I can't find the problem and solution.
I use the following code to create and append the text.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
Try
Using file As New System.IO.StreamWriter(currentdir + "\logs\" + FormClient.gametitle + "." + FormLogin.username + "_" + thisDate + "_ [" + fileNumber + "]" + ".txt", True)
file.WriteLine(TxtIssue.Text + " " + TxtWhen.Text + " " + TxtWhere.Text + " " + TxtInfo.Text)
file.WriteLine("")
End Using
Catch ex As Exception
MessageBox.Show(("Error while loading: " + ex.Message))
End Try
End Sub
Private Sub FormFeedback_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.FormClosing
thisDate = Today
Dim filenameFormat = currentdir + "\logs\" + FormClient.gametitle + "." + FormLogin.username + "_" + thisDate + "_ [" + fileNumber + "]" + ".txt"
Dim uploadFormat = Path.Combine("-removed-", filenameFormat)
My.Computer.Network.UploadFile(filenameFormat, uploadFormat, "mennovv", "mennomail98", True, 500)
End Sub
The following piece of code checks if a file exists, but I don't think this is the problem.
While My.Computer.FileSystem.FileExists(currentdir + "\logs\" + FormClient.gametitle + "." + FormLogin.username + "_" + thisDate + "_ [" + fileNumber + "]" + ".txt") = True
fileNumber += 1
End While

Image location won't write to file and Image won't load from file location

well I want to make the program write a an image location to a text file, and then when the user presses the "load" button, it reads that image location and sets it as the Image of the PictureBox, but so far I have had no success at all.
Private Sub Btn_Save_Click(sender As Object, e As EventArgs) Handles Btn_Save.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "config_card.aygo"
Dim path2 As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
Dim fs2 As FileStream = File.Create(path2)
' Add text to the file.
Dim info As Byte() =
New UTF8Encoding(True).GetBytes(
"----------Saved Card Settings----------" + vbNewLine +
"Level: " + My.Settings.Level.ToString + vbNewLine +
"NoMonster: " + My.Settings.NoMonster.ToString + vbNewLine +
"Spell: " + My.Settings.Spell.ToString + vbNewLine +
"Trap: " + My.Settings.Trap.ToString + vbNewLine +
"XYZLevel: " + My.Settings.XyzLevel.ToString + vbNewLine +
"ATKValue: " + My.Settings.ATKValue.ToString + vbNewLine +
"DEFValue: " + My.Settings.DEFValue.ToString + vbNewLine +
"AttributeID: " + My.Settings.AttributeID.ToString + vbNewLine +
"CardID: " + My.Settings.CardID.ToString)
fs.Write(info, 0, info.Length)
fs.Close()
Dim info2 As Byte() =
New UTF8Encoding(True).GetBytes(CardImage.InitialImage.ToString)
fs2.Write(info2, 0, info2.Length)
fs2.Close()
MsgBox("Configuration saved successfully!", vbInformation)
End Sub
Private Sub Btn_Load_Click(sender As Object, e As EventArgs) Handles Btn_Load.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "config_card.aygo"
Try
My.Settings.Level = CInt(GetSettingItem(path, "level"))
My.Settings.NoMonster = CInt(GetSettingItem(path, "nomonster"))
My.Settings.Spell = CBool(GetSettingItem(path, "spell"))
My.Settings.Trap = CBool(GetSettingItem(path, "trap"))
If My.Settings.NoMonster = 1 Then
If My.Settings.Spell = True Then
CardFt.Card_Spell()
Else
If My.Settings.Trap = True Then
CardFt.Card_Trap()
Else
CardFt.Card_Legendary()
End If
End If
End If
My.Settings.XyzLevel = CInt(GetSettingItem(path, "xyzlevel"))
If My.Settings.XyzLevel = 1 Then
CardFt.Card_XYZ()
End If
My.Settings.ATKValue = GetSettingItem(path, "atkvalue")
ATKText.Text = GetSettingItem(path, "atkvalue")
My.Settings.DEFValue = GetSettingItem(path, "defvalue")
DEFText.Text = GetSettingItem(path, "defvalue")
My.Settings.AttributeID = CInt(GetSettingItem(path, "attributeid"))
If My.Settings.AttributeID = 1 Then
AttributeLayer.Image = My.Resources.Earth
ElseIf My.Settings.AttributeID = 2 Then
AttributeLayer.Image = My.Resources.Water
ElseIf My.Settings.AttributeID = 3 Then
AttributeLayer.Image = My.Resources.Fire
ElseIf My.Settings.AttributeID = 4 Then
AttributeLayer.Image = My.Resources.Wind
ElseIf My.Settings.AttributeID = 5 Then
AttributeLayer.Image = My.Resources.Dark
ElseIf My.Settings.AttributeID = 6 Then
AttributeLayer.Image = My.Resources.Light
ElseIf My.Settings.AttributeID = 7 Then
AttributeLayer.Image = My.Resources.Divine
End If
My.Settings.CardID = CInt(GetSettingItem(path, "cardid"))
CardFt.Card_Loader()
If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo") Then
Try
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo")
Catch ex As Exception : End Try
End If
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures + "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
Catch ex As Exception
MsgBox("An error occured while loading the configuration file: " & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.ToString, vbExclamation)
My.Computer.Clipboard.SetText(ex.ToString)
End Try
End Sub
The error that I get from this is:
System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(String filename)
at AnimeYuGiOhCardMaker.CardMaker.Btn_Load_Click(Object sender, EventArgs e) in C:\Users\Compusys\Documents\Visual Studio 2012\Projects\Anime Yu-Gi-Oh Card Maker\Anime Yu-Gi-Oh Card Maker\Form1.vb:line 521
Now then, when the Save Button is being pressed It does not write the image location to file however it writes the following:
System.Drawing.Bitmap
This is why I get the error above.
The actual error is from here:
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures + "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
The error occurs even with an actual file path.
I tried a few different ways but none of them worked. Any help would be really appreciated. Thanks.
--
Dom
The original question has changed several times, including the exception. The current state of the question has several problems, the main one being this:
If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo") Then
Try
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyPictures _
+ "\Card Library\Configs\" + "set_cardimg.aygo")
' EMPTY CATCH !!!!!!
Catch ex As Exception : End Try
End If
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures _
+ "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
set_cardimg.aygo is just a config file which contains some text. it is not a valid image file, so you cannot create a bitmap from it.
You should open that file, read the contents into a variable, then if it is a valid location, create the bitmap from it, or better just set the picturebox .Location and let it load the image without you creating a bitmap first.

Capture 7-Zip output and exit code from a process in VB

I have the following VB.NET 4.0 console application that runs 7z.exe in a process and successfully completes with a zipped file:
Public Sub CompressFiles(sZipFileName As String, sDriveLetter As String)
Dim s7ZipCmdArgs As String = ""
Dim myProcess As New Process
Console.WriteLine()
Console.WriteLine("Scanning files...")
'Compress files
s7ZipCmdArgs = " a -r -y -xr!windows\ -xr!$Recycle.Bin\ " + sZipFileName _
+ " " + sDriveLetter + "\*.txt" _
+ " " + sDriveLetter + "\*.doc" _
+ " " + sDriveLetter + "\*.xls" _
+ " " + sDriveLetter + "\*.ppt" _
+ " " + sDriveLetter + "\*.url" _
+ " " + sDriveLetter + "\*.docx" _
+ " " + sDriveLetter + "\*.xlsx" _
+ " " + sDriveLetter + "\*.pptx" _
+ " " + sDriveLetter + "\*.pdf" _
+ " " + sDriveLetter + "\*.wav" _
+ "> C:\test\zipresults.txt"
myProcess.StartInfo.FileName = "C:\test\7-Zip\7z.exe"
myProcess.StartInfo.Arguments = s7ZipCmdArgs
myProcess.StartInfo.WorkingDirectory = "C:\test"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
myProcess.WaitForExit()
End Sub
The code executes fine except for the redirect to a text file: "> C:\test\zipresults.txt" in the s7ZipCmdArgs string variable. I'm not sure why that's not working, I've tried different sets of double and triple quotes without success. It does work in a batch file using the same string.
My second question is: How do I capture the 7Zip exit code so that I can determine if it completed successfully? It returns the following integers: 0 (No errors), 1 (Non fatal error), 2 (Fatal error), 7 (Command line error), 8 (Memory error), and 255 (User error). I'm not sure how to capture the integer so that I can decode it.
For the first part, have you tried adding a space before the > in your command args? You could also check out this answer for capturing the output in code.
For the first part, per this answer you can't redirect the standard output using > when using Process.Start(). So, you will need to remove the redirect from the arguments, set StartInfo.RedirectStandardOutput to true, and then write the output to a file in the OutputDataReceived event. Something like this:
Dim pgm = "C:\Program Files\7-Zip\7z.exe"
Dim args = "l C:\Dev\Test.zip"
Dim myProcess = New Process()
With myProcess.StartInfo
.FileName = pgm
.Arguments = args
.WorkingDirectory = "C:\Dev"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardOutput = True
End With
Using out = New StreamWriter("C:\Dev\test.txt")
AddHandler myProcess.OutputDataReceived,
Sub(sender, e)
out.WriteLine(e.Data)
End Sub
myProcess.Start()
myProcess.BeginOutputReadLine()
myProcess.WaitForExit()
End Using
For the second, myProcess.ExitCode will have the result after the WaitForExit() call.