如何使用电子邮件功能将文档文件附加到电子邮件? [英] How to attach a document file to email using email functions?
问题描述
您好,
我正在尝试使用电子邮件功能将文档文件附加到电子邮件中,但我没有获得附件。
任何人都可以帮忙解决问题吗?
这是我的代码:
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用System。 Web;
使用System.Web.Security;
使用System.Web.UI;
使用System.Web.UI.WebControls;
使用System.DirectoryServices;
使用Gucci.CustomerInsightRequests.Classes;
使用Gucci.CustomerInsightRequests.DataAccess;
使用System.Text;
$
使用System.Collections.Specialized;
使用System.Data.SqlClient;
使用System.Configuration;
使用System.Net.Mail;
$
命名空间Gucci.CustomerInsightRequests
{
    public partial class RequestForm:System.Web.UI.Page
  {
      protected void Page_Load(object sender,EventArgs e)
      {
          //如果页面是第一次加载而不是PostBack
          if(!Page.IsPostBack)
          {
              //如果Page.User不为null(表示有一个有效的验证用户访问该页面)
              if(User!= null)
              {
                  string displayName = string.Empty;
                  string emailAddress = string.Empty;
                  //调用函数从Active Directory获取Page.User的显示名称和电子邮件地址
                  if(UtilityFunctions.GetADUserNameAndEmail(User.Identity.Name,out displayName,out emailAddress))
                  {
                      //根据Page.User为
设置请求者名称和请求者或电子邮件文本框字段为默认值。                       //创建新的Reqeust
                      txtRequestorName.Text = displayName;
                      txtRequestorEmail.Text = emailAddress;
                  }
              }¥b $ b               //使用"业务"类别从数据库LOV表填充Business Dropdown控件。作为过滤器
              UtilityFunctions.populate(business," BUSINESS");
              //为"Date Required"设置Compare Validator值文本框从今天开始2周(14天)
              compValidatorDateRequired.ValueToCompare = DateTime.Today.AddDays(14).ToShortDateString();
              //将焦点设置为商店ID文本框
              txtStoreID.Focus();
$
              //使用类别"产品"从数据库LOV表填充产品下拉控件。作为过滤器
              UtilityFunctions.populate(ddlproduct," product");
          }¥b $ b       }
      protected void btnSubmit_Click(object sender,EventArgs e)
      {
          if(Page.IsValid)
          {
              //使用连接到RMKT数据库的RMKT实体
             使用(RMKTEntities context = new RMKTEntities())
              {
                 试试
                  {
                      //创建新的客户洞察请求
                      CustomerInsightRequest newRequest = new CustomerInsightRequest();
                      //根据表格上的控件将字段设置为其值
                      newRequest.Username = User!= null&& User.Identity.Name!= null? User.Identity.Name:"错误";
                      newRequest.CreateDate = DateTime.Now;
                      newRequest.RequestorName = txtRequestorName.Text;
                      newRequest.RequestorEmail = txtRequestorEmail.Text;
$
                      //如果没有输入任何值,则将StoreID设置为null
                      if(string.IsNullOrEmpty(txtStoreID.Text))
                          newRequest.Store = null;
                     否则
                          newRequest.Store = txtStoreID.Text;
                      //如果未输入值,则将businessID设置为null
                      int businessVal = int.TryParse(business.SelectedValue,out businessVal)
                                                    ? businessVal
                                                    :-1;
                      if(businessVal == -1)
                          newRequest.businessID = null;
                     否则
                          newRequest.businessID = businessVal;
$
                      int productVal = int.TryParse(ddlproduct.SelectedValue,out productVal)
                                                    ? productVal
                                                    :-1;
                      newRequest.productID = productVal;
$
                      string filename = Path.GetFileName(fileUpload.PostedFile.FileName);
                      Stream str = fileUpload.PostedFile.InputStream;
                      BinaryReader br = new BinaryReader(str);
                     字节[] size = br.ReadBytes((int)str.Length);
                      newRequest.Attachments = size;
                        Attachment att = new Attachment(fileUpload.PostedFile.InputStream,Path.GetFileName(fileUpload.PostedFile.FileName));
$ b
                      newRequest.Objective = txtRequestObjective.Text;
                      newRequest.Description = txtRequestDescription.Text;
                      DateTime reqDate;
                      //如果以某种方式没有为"Date Required"提供Date值然后将其设置为允许的最大日期
                      newRequest.RequireDate = DateTime.TryParse(txtDateRequired.Text,out reqDate)
                                                   ? reqDate
                                                  :DateTime.MaxValue;
                      //将状态指定为已打开
                      newRequest.StatusID = Constants.STATUS_OPENID;
                      context.CustomerInsightRequests.AddObject(newRequest);
                      context.SaveChanges();
                      //构建通知电子邮件以发送给用户和角色中的任何用户:营销
                      ListDictionary replacements = new ListDictionary();
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacements.Add("<%RequestID%>",newRequest.RequestID.ToString());
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacementments.Add("<%CreateDate%>",newRequest.CreateDate.ToShortDateString());
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacements.Add("<%RequestorName%>",newRequest.RequestorName.ToString());
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacements.Add("<%Store%>",txtStoreID.Text.ToString());
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacementments.Add("<%business%>",business.SelectedItem.Text);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacementments.Add("<%product%>",ddlproduct.SelectedItem.Text);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacements.Add(QUOT;<%目标%GT;" ;, newRequest.Objective.Replace(char.ConvertFromUtf32(13),QUOT;<峰; br />"));
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; replacements.Add(QUOT;<%说明%GT;" ;, newRequest.Description.Replace(char.ConvertFromUtf32(13),QUOT;<峰; br />"));
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string subject = string.Format(" Customer Insight Request({0})",
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; newRequest.RequestID.ToString());
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //发送电子邮件异步
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //电子邮件也发送给营销角色中的用户
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; EmailFunctions.Send(newRequest.RequestorEmail,subject," NewRequest",true,replacementments,SiteRoles.MARKETING,true,att);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //创建对话框消息框以向用户显示新请求已创建。
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string alertMessage =
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;的String.Format(
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;"请求(ID { 0})已创建。您很快就会收到一封确认电子邮件。",
newRequest.RequestID.ToString());
$
$
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; runjQueryCode(" $('div #ui-dialog-message')。html('" + alertMessage +"'); $('div#ui-dialog-message')。dialog('open'); ");)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; catch(Exception exp)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;抛出新的异常("错误:无法提交请求 - " + exp.Message.ToString(),exp);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; ///< summary>
&NBSP; &NBSP; &NBSP; ///单击表单上的"取消"按钮时调用
&NBSP; &NBSP; &NBSP; ///< / summary>
&NBSP; &NBSP; &NBSP; ///< param name =" sender">< / param>
&NBSP; &NBSP; &NBSP; ///< param name =" e">< / param>
&NBSP; &NBSP; &NBSP; protected void btnCancel_Click(object sender,EventArgs e)
&NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //将用户重定向到default.aspx页面
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; Response.Redirect(" Default.aspx");
&NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; #region PageUtilities
&NBSP; &NBSP; &NBSP; private string getjQueryCode(string jsCodetoRun)
&NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; StringBuilder sb = new StringBuilder();
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; sb.AppendLine(QUOT; $(文件)。就绪(函数(){");
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; sb.AppendLine(jsCodetoRun); <无线电通信/>
sb.AppendLine("});");
$
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; return sb.ToString();
&NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; private void runjQueryCode(string jsCodetoRun)
&NBSP; &NBSP; &NBSP; {
$
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; ScriptManager requestSM = ScriptManager.GetCurrent(this);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(requestSM!= null&& requestSM.IsInAsyncPostBack)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; ScriptManager.RegisterClientScriptBlock(这一点,
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; typeof运算(页),
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP ; Guid.NewGuid()。ToString(),<登记/>
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP ; getjQueryCode(jsCodetoRun),
true);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;否则
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; ClientScript.RegisterClientScriptBlock(typeof运算(页),
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP ;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Guid.NewGuid()的ToString(),
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP ; getjQueryCode(jsCodetoRun ),&
true);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; #endregion
&NBSP; }
}
$
//来自电子邮件功能文件的代码
I am trying to attach a document file to email using email functions but I am not getting attachment.
Can anyone help to resolve the issue?
Here is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using Gucci.CustomerInsightRequests.Classes;
using Gucci.CustomerInsightRequests.DataAccess;
using System.Text;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;
namespace Gucci.CustomerInsightRequests
{
public partial class RequestForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//If the page is loading for the first time and is not a PostBack
if(!Page.IsPostBack)
{
//If the Page.User is not null (meaning there is a valid autheticated user accessing the page)
if (User != null)
{
string displayName = string.Empty;
string emailAddress = string.Empty;
//Call function to get the Page.User's display name and email address from Active Directory
if(UtilityFunctions.GetADUserNameAndEmail(User.Identity.Name, out displayName, out emailAddress))
{
//Set the Requestor Name and Requestor Email textbox fields to default values based on the Page.User
//creating the new Reqeust
txtRequestorName.Text = displayName;
txtRequestorEmail.Text = emailAddress;
}
}
//Populate the Business Dropdown control from the database LOV table using the Category "BUSINESS" as a filter
UtilityFunctions.populate(business, "BUSINESS");
//Set the Compare Validator value for the "Date Required" textbox to 2 weeks (14 days) from Today
compValidatorDateRequired.ValueToCompare = DateTime.Today.AddDays(14).ToShortDateString();
//Set Focus to Store ID text box
txtStoreID.Focus();
//Populate the product Dropdown control from the database LOV table using the Category "product" as a filter
UtilityFunctions.populate(ddlproduct, "product");
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//use the RMKT Entity connected to the RMKT database
using (RMKTEntities context = new RMKTEntities())
{
try
{
//Create New Customer Insight Request
CustomerInsightRequest newRequest = new CustomerInsightRequest();
//Set the fields to their values based on the controls on the Form
newRequest.Username = User != null && User.Identity.Name != null ? User.Identity.Name : "Error";
newRequest.CreateDate = DateTime.Now;
newRequest.RequestorName = txtRequestorName.Text;
newRequest.RequestorEmail = txtRequestorEmail.Text;
//set the StoreID to null if no value was entered
if (string.IsNullOrEmpty(txtStoreID.Text))
newRequest.Store = null;
else
newRequest.Store = txtStoreID.Text;
//Set the businessID to null if not value was entered
int businessVal = int.TryParse(business.SelectedValue, out businessVal)
? businessVal
: -1;
if (businessVal == -1)
newRequest.businessID = null;
else
newRequest.businessID = businessVal;
int productVal = int.TryParse(ddlproduct.SelectedValue, out productVal)
? productVal
: -1;
newRequest.productID = productVal;
string filename = Path.GetFileName(fileUpload.PostedFile.FileName);
Stream str = fileUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(str);
Byte[] size = br.ReadBytes((int)str.Length);
newRequest.Attachments = size;
Attachment att = new Attachment(fileUpload.PostedFile.InputStream, Path.GetFileName(fileUpload.PostedFile.FileName));
newRequest.Objective = txtRequestObjective.Text;
newRequest.Description = txtRequestDescription.Text;
DateTime reqDate;
//if somehow a Date value is not provided for "Date Required" then set it to the Maximum Date allowed
newRequest.RequireDate = DateTime.TryParse(txtDateRequired.Text, out reqDate)
? reqDate
: DateTime.MaxValue;
//Assign the Status as open
newRequest.StatusID = Constants.STATUS_OPENID;
context.CustomerInsightRequests.AddObject(newRequest);
context.SaveChanges();
//Build Notification Email to send to User and any Users in the Role:Marketing
ListDictionary replacements = new ListDictionary();
replacements.Add("<%RequestID%>", newRequest.RequestID.ToString());
replacements.Add("<%CreateDate%>", newRequest.CreateDate.ToShortDateString());
replacements.Add("<%RequestorName%>", newRequest.RequestorName.ToString());
replacements.Add("<%Store%>", txtStoreID.Text.ToString());
replacements.Add("<%business%>", business.SelectedItem.Text);
replacements.Add("<%product%>", ddlproduct.SelectedItem.Text);
replacements.Add("<%Objective%>", newRequest.Objective.Replace(char.ConvertFromUtf32(13), "<br/>"));
replacements.Add("<%Description%>", newRequest.Description.Replace(char.ConvertFromUtf32(13),"<br/>"));
string subject = string.Format("Customer Insight Request ({0})",
newRequest.RequestID.ToString());
//Send Email Async
//The email is also sent the the users in the Marketing Role
EmailFunctions.Send(newRequest.RequestorEmail, subject, "NewRequest", true, replacements, SiteRoles.MARKETING, true, att);
//Create dialog message box to show user that the new Request was created.
string alertMessage =
string.Format(
"Request (ID {0}) created. You should receive a confirmation email shortly.",
newRequest.RequestID.ToString());
runjQueryCode("$('div#ui-dialog-message').html('" + alertMessage + "');$('div#ui-dialog-message').dialog('open');");
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Submit Request - " + exp.Message.ToString(), exp);
}
}
}
}
/// <summary>
/// Called when the Cancel button on the form is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnCancel_Click(object sender, EventArgs e)
{
//redirect the user to the default.aspx page
Response.Redirect("Default.aspx");
}
#region PageUtilities
private string getjQueryCode(string jsCodetoRun)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("$(document).ready(function() {");
sb.AppendLine(jsCodetoRun);
sb.AppendLine(" });");
return sb.ToString();
}
private void runjQueryCode(string jsCodetoRun)
{
ScriptManager requestSM = ScriptManager.GetCurrent(this);
if (requestSM != null && requestSM.IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptBlock(this,
typeof(Page),
Guid.NewGuid().ToString(),
getjQueryCode(jsCodetoRun),
true);
}
else
{
ClientScript.RegisterClientScriptBlock(typeof(Page),
Guid.NewGuid().ToString(),
getjQueryCode(jsCodetoRun),
true);
}
}
#endregion
}
}
//Code from Email Functions file
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Net.Mail;
使用System.Configuration;
使用System.IO;
使用System。 Collections.Specialized;
使用System.Web.UI.WebControls;
使用System.Web.Security;
namespace Gucci.CustomerInsightRequests.Classes
{
&NBSP;公共类电子邮件功能
&NBSP; {
$
&NBSP; &NBSP; &NBSP;公共静态无效发送(串pToAddress,串pSubject,串messageTemplate,布尔pIsBodyHtml,ListDictionary替换,串ccRoleGroup,布尔pAsync,附件[] pAttachments)
&NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //从web.config获取电子邮件服务器和设置的参数
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string smtpServer = ConfigurationManager.AppSettings [" Email:SmtpServer"];
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; int smtpPort = int.Parse(ConfigurationManager.AppSettings [" Email:SmtpPort"]);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string smtpUsername = ConfigurationManager.AppSettings [" Email:SmtpUsername"];
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string smtpPassword = ConfigurationManager.AppSettings [" Email:SmtpPassword"];
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string fromAddress = ConfigurationManager.AppSettings [" Email:FromAddress"];
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string bccAddress = ConfigurationManager.AppSettings [" Email:BCCAddress"];
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //加载用于电子邮件的模板
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //模板位于App_Date / messages文件夹中$
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string physicalPath = HttpContext.Current.Server.MapPath("〜/ App_Data / messages /" + messageTemplate.ToString()+" .htm");
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(!File.Exists(physicalPath))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;抛出新的ArgumentException("无效的MailTemplate传入NotificationManager","messageTemplate");
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; MailDefinition md = new MailDefinition();
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; md.BodyFileName = physicalPath;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; md.Subject = pSubject;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; md.From = fromAddress;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; md.IsBodyHtml = pIsBodyHtml;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; System.Net.Mail.MailMessage mm;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //处理您已包含的所有替换变量。
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; mm = md.CreateMailMessage(pToAddress,replacements,new System.Web.UI.Control());
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //如果在web.config中指定了BCCAddress,那么请在邮件中包含该内容
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(!string.IsNullOrEmpty(bccAddress))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; mm.Bcc.Add(bccAddress);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //包含任何附件 - 将来使用
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; for(int a = 0; a< pAttachments.Length; a ++)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; mm.Attachments.Add(pAttachments [a]);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; // CC指定的任何角色组。任何具有指定角色的用户(例如:营销)都将添加到电子邮件的CC上。
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(!string.IsNullOrEmpty(ccRoleGroup))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string [] roleUsers = Roles.GetUsersInRole(ccRoleGroup);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; foreach(roleUser中的string roleuser)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string displayName = string.Empty;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; string emailAddress = string.Empty;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //调用函数从Active Directory获取用户的显示名称和电子邮件地址
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(UtilityFunctions.GetADUserNameAndEmail(roleuser,out displayName,out emailAddress))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; mm.CC.Add(新邮件地址(emailAddress,displayName));
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; //发送Asyncronously以便页面无需等待发送电子邮件
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(pAsync)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;使用(新的SynchronizationContextSwitcher())
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtpServer);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.Port = smtpPort;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(!string.IsNullOrEmpty(smtpPassword))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.UseDefaultCredentials = true;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.Credentials = new System.Net.NetworkCredential(smtpUsername,smtpPassword);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.SendAsync(mm,null);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;否则
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtpServer);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; if(!string.IsNullOrEmpty(smtpPassword))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.UseDefaultCredentials = true;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.Credentials = new System.Net.NetworkCredential(smtpUsername,smtpPassword);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; smtpClient.Send(mm);
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; }¥b $ b &NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; public static void Send(string pToAddress,string pSubject,string messageTemplate,bool pIsBodyHtml,ListDictionary replacements,string ccRoleGroup,Attachment att)
&NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP;发送(pToAddress,pSubject,messageTemplate,pIsBodyHtml,替换,ccRoleGroup,false,新附件[] {});
&NBSP; &NBSP; &NBSP; }
&NBSP; &NBSP; &NBSP; public static void Send(string pToAddress,string pSubject,string messageTemplate,bool pIsBodyHtml,ListDictionary replacements,string ccRoleGroup,bool pAsync,Attachment att)
&NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP;发送(pToAddress,pSubject,messageTemplate,pIsBodyHtml,替换,ccRoleGroup,pAsync,新附件[] {});
&NBSP; &NBSP; &NBSP; }
&NBSP; }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Configuration;
using System.IO;
using System.Collections.Specialized;
using System.Web.UI.WebControls;
using System.Web.Security;
namespace Gucci.CustomerInsightRequests.Classes
{
public class EmailFunctions
{
public static void Send(string pToAddress, string pSubject, string messageTemplate, bool pIsBodyHtml, ListDictionary replacements, string ccRoleGroup, bool pAsync, Attachment[] pAttachments)
{
//Get Parameters from web.config for email server and settings
string smtpServer = ConfigurationManager.AppSettings["Email:SmtpServer"];
int smtpPort = int.Parse(ConfigurationManager.AppSettings["Email:SmtpPort"]);
string smtpUsername = ConfigurationManager.AppSettings["Email:SmtpUsername"];
string smtpPassword = ConfigurationManager.AppSettings["Email:SmtpPassword"];
string fromAddress = ConfigurationManager.AppSettings["Email:FromAddress"];
string bccAddress = ConfigurationManager.AppSettings["Email:BCCAddress"];
//Load the template to use for the email message
//The templates are located in the App_Date/messages folder
string physicalPath = HttpContext.Current.Server.MapPath("~/App_Data/messages/" + messageTemplate.ToString() + ".htm");
if (!File.Exists(physicalPath))
{
throw new ArgumentException("Invalid MailTemplate Passed into the NotificationManager", "messageTemplate");
}
MailDefinition md = new MailDefinition();
md.BodyFileName = physicalPath;
md.Subject = pSubject;
md.From = fromAddress;
md.IsBodyHtml = pIsBodyHtml;
System.Net.Mail.MailMessage mm;
//Processes all of the replacement vars that you've included.
mm = md.CreateMailMessage(pToAddress, replacements, new System.Web.UI.Control());
//If a BCCAddress was specified in the web.config then include that in the message
if(!string.IsNullOrEmpty(bccAddress))
mm.Bcc.Add(bccAddress);
//Include any Attachments - future use
for (int a = 0; a < pAttachments.Length; a++)
{
mm.Attachments.Add(pAttachments[a]);
}
//CC any Role Group specified. Any user that has the Role specified (example: Marketing) would be added on the CC of the email message
if (!string.IsNullOrEmpty(ccRoleGroup))
{
string[] roleUsers = Roles.GetUsersInRole(ccRoleGroup);
foreach (string roleuser in roleUsers)
{
string displayName = string.Empty;
string emailAddress = string.Empty;
//call function to get a user's display name and email address from Active Directory
if (UtilityFunctions.GetADUserNameAndEmail(roleuser, out displayName, out emailAddress))
{
mm.CC.Add(new MailAddress(emailAddress, displayName));
}
}
}
//Send Asyncronously so the page does not have to wait for the email to be sent
if (pAsync)
{
using (new SynchronizationContextSwitcher())
{
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtpServer);
smtpClient.Port = smtpPort;
if(!string.IsNullOrEmpty(smtpPassword))
{
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(smtpUsername, smtpPassword);
}
smtpClient.SendAsync(mm, null);
}
}
else
{
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtpServer);
if (!string.IsNullOrEmpty(smtpPassword))
{
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(smtpUsername, smtpPassword);
}
smtpClient.Send(mm);
}
}
public static void Send(string pToAddress, string pSubject, string messageTemplate, bool pIsBodyHtml, ListDictionary replacements, string ccRoleGroup, Attachment att)
{
Send(pToAddress, pSubject, messageTemplate, pIsBodyHtml,replacements, ccRoleGroup, false, new Attachment[] { });
}
public static void Send(string pToAddress, string pSubject, string messageTemplate, bool pIsBodyHtml, ListDictionary replacements, string ccRoleGroup, bool pAsync, Attachment att)
{
Send(pToAddress, pSubject, messageTemplate, pIsBodyHtml, replacements, ccRoleGroup, pAsync, new Attachment[] { });
}
}
}
任何帮助都将不胜感激。
Any help would be greatly appreciated.
Thx。
OK29
推荐答案
行中是否有任何记录 mm.Attachments.Add(pAttachments [a]);?
存在文件并且文件是否有效?
Exist files and are files valid?
这篇关于如何使用电子邮件功能将文档文件附加到电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!