发送带有存储在数据库中的多个附件的电子邮件(ASP.NET C#)
作者:互联网
我希望发送包含多个简历的电子邮件.每个学生都有一个配置文件,其中附有简历(一些学生有多个简历),并将这些简历存储在数据库中.用户搜索符合特定条件的学生,然后将学生的简历通过电子邮件发送给潜在的雇主.
数据库:
cvID - int
UserName - varchar(50)
FileName - varchar(50)
FileType - nvarchar(50)
Data - varbinary(MAX)
进行搜索时,合适的学生会在结果中显示每个带有可用简历的下拉框.用户从希望附加到电子邮件的下拉列表框中选择“继续”,单击“附加”,然后将FileName添加到电子邮件区域的ListBox中.
用户选择了希望附加的所有简历后,便填写剩余的电子邮件字段…收件人,发件人,主题,消息等.当用户单击“发送”时,我需要代码以附加附件中列出的文件.从数据库ListBox并发送电子邮件.
ASPX.CS页面
使用System.Net.Mail
protected void emlSend_Click(object sender, EventArgs e)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(txtFrom.Text);
email.To.Add(txtTo.Text);
email.Subject = txtSub.Text;
email.Body = txtMsg.Text;
//Loop through lstFiles to get all values
foreach (ListItem item in lstFiles.Items)
{
if (item.Selected)
{
//Save value to string
string lstItem = item.Text;
string lstValue = item.Value;
//Connect to Server
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
//Use value in Select statement
cmd.CommandText = "SELECT FileName, FileType, Data from CVData where cvID = '" + lstValue + "'";
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
//Get CV Data
sdr.Read();
bytes = (byte[])sdr["Data"];
fileName = sdr["FileName"].ToString();
//Attach Data as Email Attachment
email.Attachments.Add(... //This is where I am now stuck
}
con.Close();
}
}
}
}
使用以下内容…
email.Attachments.Add(new Attachment(new MemoryStream(bytes, fileName)));
给我这个错误:
编译器错误消息:CS1502:最佳重载方法匹配’System.IO.MemoryStream.MemoryStream(byte [],bool)’有一些无效的参数
如果我尝试这种错误方式,请告诉我.这是我第一次尝试做这样的事情,所以任何帮助将不胜感激!
解决方法:
您需要使用System.Net.Mail命名空间.
System.Web.Mail.MailMessage已过时.
这是您向MailMessage添加附件的方式.
// assumption is that the dropdown values contain a key to the file
// contents (resume) in the DB and the contents are retrieved as a
// byte array.
if (lstFiles != null)
{
foreach (var fileName in lstFiles)
{
int cvId = 42; // can come from dropdown etc. basically a key to the file.
byte[] resumeBytes = GetResumeFromDatabaseAsBytes(cvId);
email.Attachments.Add(new Attachment(new MemoryStream(resumeBytes, fileName)));
}
}
public static byte[] GetResumeFromDatabaseAsBytes(int cvID)
{
var connectionString = "YOUR_CONNECTION_STRING";
using (var sqlConnection = new SqlConnection(connectionString))
{
using (var sqlCommand = new SqlCommand("SELECT TOP 1 FileName, FileType, Data From RESUME_TABLE_NAME Where cvID = " + cvID, sqlConnection))
{
using (var reader = sqlCommand.ExecuteReader())
{
if (reader.Read())
{
// e.g. John_Doe.docx
string fileName = reader["FileName"].ToString() + "." + reader["FileType"].ToString();
byte[] cvData = (byte[])reader["Data"];
//return cvData;
}
}
}
}
}
以上只是获取简历内容的示例.您可以通过传递正确的参数在一次通话中获得所有简历.让我们知道您正在使用的数据访问方法.
标签:email-attachments,email,asp-net,c 来源: https://codeday.me/bug/20191121/2055452.html