2017-02-23 50 views
-1

我想上传图像到数据库,并在用户单击保存按钮时发送电子邮件。当用户点击保存时数据库上传工作正常,但电子邮件没有正确发送。如何在c#窗体中的邮件图像框中添加图像

我是否正确格式化了msg.body

try 
{ 
    u.Open(); 
    SqlCommand i = new SqlCommand("insert into BMS values('" + p + "')", u); 
    i.ExecuteNonQuery(); 

    MailMessage Msg = new MailMessage(); 

    Msg.From = new MailAddress("[email protected]", "*****"); 
    Msg.To.Add("[email protected]"); 

    string _fname = pictureBox1.ToString(); 

    Msg.Attachments.Add(new Attachment(_fname)); 
    Msg.Subject = "user credential sent from bank "; 
    Msg.Body = "<img [email protected]'+ pictureBox.Image + />";     
    Msg.IsBodyHtml = true; 

    SmtpClient smtp = new SmtpClient(); 
    smtp.Host = "smtp.gmail.com"; 
    smtp.Port = 587; 
    smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "****"); 
    smtp.EnableSsl = true; 
    smtp.Send(Msg); 

    MessageBox.Show("Data inserted successfully and data's mailed "); 

    u.Close(); 
} 
catch (Exception ex) 
{ 
    Console.WriteLine("{0} Exception caught.", ex); 
} 
+0

除此之外,似乎并不像是发送实际图像部分的方式..当您尝试发送它时会发生什么?它运行哪些代码行?编号预计你会得到一个单行文字说图像或其中的东西的邮件 – BugFinder

+0

我认为,在msg.body中的代码是错误的 - 可以写什么代码? – gokul

+0

实际上图像正在保存在数据库中,但邮件部分不工作,我喜欢发送该图像形式邮件编号作为附件当保存点击 – gokul

回答

1

如果你想显示在电子邮件正文中的图像,你需要上传图像的任何网站,并把电子邮件像下面发送图像代码

Msg.Body = "<img src=" + pic_url + " />"; 

尝试,此外,我建议你添加值sqlcommand中的参数

SqlConnection con = new SqlConnection("connection string"); 
     SqlCommand com = new SqlCommand("insert into BMS values(@value1)", con); 
     com.Parameters.AddWithValue("@value1", p); 
     try 
     { 
      com.Connection.Open(); 
      com.ExecuteNonQuery(); 

      MailMessage Msg = new MailMessage(); 
      Msg.From = new MailAddress("your email", "your display name"); 
      Msg.To.Add("to user name"); 
      string _fname = pictureBox1.ToString(); 

      Image image = pictureBox1.Image; 

      System.IO.MemoryStream stream = new System.IO.MemoryStream(); 
      image.Save(stream, ImageFormat.Jpeg); 
      stream.Position = 0; 

      Msg.Attachments.Add(new Attachment(stream, "Screenshot.jpg")); 

      Msg.Subject = "user credential sent from bank "; 


      Msg.Body = "content here "; 
      Msg.IsBodyHtml = true; 
      SmtpClient smtp = new SmtpClient(); 
      smtp.Host = "mail.cidcode.net"; 
      smtp.Port = 587; 
      smtp.Credentials = new System.Net.NetworkCredential("your email", "your password"); 
      smtp.Send(Msg); 

      MessageBox.Show("Data inserted successfully and data's mailed "); 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Test " + ex.Message); 
      Console.WriteLine("{0} Exception caught.", ex); 
     } 
     finally 
     { 
      com.Connection.Close(); 
      com.Dispose(); 
     } 
+0

感谢分享这个,我有一个小的怀疑,在这个代码中,在@ value1,我应该写什么? (com.Parameters.AddWithValue(“@ value1”,p);) – gokul

+0

@ value1是任何参数,p是您发送到数据库的参数值 –

+0

代码没有错误,它运行完美,但是当我点击保存并继续我收到此消息“测试交易失败,服务器响应发送addrss因垃圾邮件过滤器而未被接受”帮助我清除此错误消息并发送邮件 – gokul