MailDefinition Classe
Definição
Permite que um controle crie mensagens de email de arquivos de texto ou cadeias de caracteres.Allows a control to create email messages from text files or strings. Essa classe não pode ser herdada.This class cannot be inherited.
public ref class MailDefinition sealed : System::Web::UI::IStateManager
[System.ComponentModel.Bindable(false)]
[System.ComponentModel.TypeConverter(typeof(System.Web.UI.WebControls.EmptyStringExpandableObjectConverter))]
public sealed class MailDefinition : System.Web.UI.IStateManager
[<System.ComponentModel.Bindable(false)>]
[<System.ComponentModel.TypeConverter(typeof(System.Web.UI.WebControls.EmptyStringExpandableObjectConverter))>]
type MailDefinition = class
interface IStateManager
Public NotInheritable Class MailDefinition
Implements IStateManager
- Herança
-
MailDefinition
- Atributos
- Implementações
Exemplos
O exemplo de código a seguir cria uma mensagem de email da Internet de uma página Web Forms.The following code example creates an Internet email message from a Web Forms page. Você pode inserir o texto da mensagem no formulário ou inserir o nome de um arquivo de texto a ser usado como o corpo do email.You can either enter the text of the message in the form or enter the name of a text file to use as the body of the mail. O código define duas substituições de cadeia de caracteres para a mensagem: a lista de destinatários da caixa de texto do formulário substituirá a cadeia de caracteres " <%To%> ", e o texto especificado na From Propriedade substituirá a cadeia de caracteres " <%From%> ".The code defines two string replacements for the message: the recipient list from the form's To text box will replace the string "<%To%>", and the text specified in the From property will replace the string "<%From%>".
Na página Web Forms que esse código gera, você pode clicar em criar email e exibir somente para criar uma mensagem de email e exibir as propriedades do MailMessage objeto na página da Web.On the Web Forms page that this code generates, you can click Create email and display only to create an email message and display the properties of the MailMessage object in the Web page. Clique em criar email e enviar para exibir a mensagem de email na página da Web e enviar a mensagem para os destinatários usando email da Internet.Click Create email and send to both display the email message in the Web page and send the message to the recipients using Internet email.
Importante
Esse controle tem uma caixa de texto que aceita a entrada do usuário, que é uma possível ameaça à segurança.This control has a text box that accepts user input, which is a potential security threat. Por padrão, as páginas da Web do ASP.NET validam que a entrada do usuário não inclui elementos de script ou HTML.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Para obter mais informações, consulte Visão geral de explorações de script.For more information, see Script Exploits Overview.
<%@ page language="C#"%>
<%@ import namespace="System.Net.Mail"%>
<%@ import namespace="System.Reflection"%>
<%@ import namespace="System.Collections.Specialized"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
HtmlTable ShowMessage(System.Net.Mail.MailMessage msg)
{
HtmlTable table = new HtmlTable();
HtmlTableRow topRow = new HtmlTableRow();
HtmlTableCell fieldHeaderCell = new HtmlTableCell();
HtmlTableCell valueHeaderCell = new HtmlTableCell();
fieldHeaderCell.InnerText = "Field";
topRow.Cells.Add(fieldHeaderCell);
valueHeaderCell.InnerText = "Value";
topRow.Cells.Add(valueHeaderCell);
table.Rows.Add(topRow);
foreach(PropertyInfo p in msg.GetType().GetProperties())
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell labelCell = new HtmlTableCell();
HtmlTableCell valueCell = new HtmlTableCell();
if (!((p.Name == "Headers") ||
(p.Name == "Fields") ||
(p.Name == "Attachments")))
{
labelCell.InnerText = String.Format("{0}",p.Name);
row.Cells.Add(labelCell);
valueCell.InnerText = String.Format("{0}",p.GetValue(msg,null));
row.Cells.Add(valueCell);
}
table.Rows.Add(row);
}
return table;
}
System.Net.Mail.MailMessage CreateMessage()
{
// <Snippet2>
MailDefinition md = new MailDefinition();
// </Snippet2>
// <Snippet3>
md.BodyFileName = sourceMailFile.Text;
// </Snippet3>
// <Snippet4>
md.CC = sourceCC.Text;
// </Snippet4>
// <Snippet5>
md.From = sourceFrom.Text;
// </Snippet5>
// <Snippet6>
md.Subject = sourceSubject.Text;
// </Snippet6>
// <Snippet10>
if (sourcePriority.SelectedValue == "Normal")
{
md.Priority = MailPriority.Normal;
}
else if (sourcePriority.SelectedValue == "High")
{
md.Priority = MailPriority.High;
}
else if (sourcePriority.SelectedValue == "Low")
{
md.Priority = MailPriority.Low;
}
// </Snippet10>
// <Snippet7>
ListDictionary replacements = new ListDictionary();
replacements.Add("<%To%>",sourceTo.Text);
replacements.Add("<%From%>", md.From);
// </Snippet7>
if (true == useFile.Checked)
{
// <Snippet8>
System.Net.Mail.MailMessage fileMsg;
fileMsg = md.CreateMailMessage(sourceTo.Text, replacements, this);
// </Snippet8>
return fileMsg;
}
else
{
// <Snippet9>
System.Net.Mail.MailMessage textMsg;
textMsg = md.CreateMailMessage(sourceTo.Text, replacements, sourceBodyText.Text, this);
// </Snippet9>
return textMsg;
}
}
void createEMail_Click(object sender, System.EventArgs e)
{
System.Net.Mail.MailMessage msg = CreateMessage();
PlaceHolder1.Controls.Add(ShowMessage(msg));
}
void sendEMail_Click(object sender, System.EventArgs e)
{
System.Net.Mail.MailMessage msg = CreateMessage();
PlaceHolder1.Controls.Add(ShowMessage(msg));
errorMsg.Text = String.Empty;
try {
SmtpClient sc = new SmtpClient();
sc.Send(msg);
}
catch (HttpException ex) {
errorMsg.Text = ex.ToString();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Create an email message</title>
</head>
<body>
<form id="Form1" runat="server">
<table id="Table1" cellspacing="1"
style="padding:1; width:450px; text-align:center">
<tr>
<td align="center" colspan="3">
<h3>Create an email message</h3>
</td>
</tr>
<tr>
<td align="right">To:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceTo" runat="server" columns="54">
</asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator1"
runat="server" errormessage="*" controltovalidate="sourceTo">
</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
<td align="right">Cc:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceCC" runat="server" columns="54">
</asp:textbox> </td>
</tr>
<tr>
<td align="right">From:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceFrom" runat="server" columns="54">
</asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator2"
runat="server" errormessage="*" controltovalidate="sourceFrom">
</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
<td align="right">Subject:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceSubject" runat="server" columns="54">
</asp:textbox> </td>
</tr>
<tr>
<td align="right">
Priority</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:dropdownlist id="sourcePriority" runat="server">
<asp:listitem value="Low">Low</asp:listitem>
<asp:listitem value="Normal" selected="true">Normal
</asp:listitem>
<asp:listitem value="High">High</asp:listitem>
</asp:dropdownlist> </td>
<td>
</td>
</tr>
<tr>
<td align="right">Source:</td>
<td style="WIDTH: 10px">
</td>
<td>
<table id="Table2" cellspacing="1" cellpadding="1" width="100%">
<tr>
<td style="WIDTH: 100px">
<asp:radiobutton id="useFile" runat="server" text="Use file"
width="80px" groupname="textSource" checked="True">
</asp:radiobutton> </td>
<td style="WIDTH: 11px">
</td>
<td>
<p style="text-align:right">File name:</p>
</td>
<td>
<asp:textbox id="sourceMailFile" runat="server" columns="22">
mail.txt</asp:textbox> </td>
</tr>
<tr>
<td style="WIDTH: 100px">
<asp:radiobutton id="useText" runat="server"
text="Enter text" width="80px" height="22px"
groupname="textSource">
</asp:radiobutton> </td>
<td style="WIDTH: 11px">
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</td>
<td> </td>
</tr>
<tr>
<td align="center" colspan="3">
<asp:textbox id="sourceBodyText" runat="server" columns="51"
textmode="MultiLine" rows="15">
</asp:textbox> </td>
</tr>
<tr>
<td align="center" colspan="3">
<asp:button id="createEMail" runat="server"
text="Create email and display only"
onclick="createEMail_Click">
</asp:button>
<asp:button id="sendEMail" runat="server"
text="Create email and send">
</asp:button></td>
</tr>
</table>
<p> </p>
<p>
<asp:placeholder id="PlaceHolder1" runat="server">
</asp:placeholder>
</p>
<p>
<asp:literal id="errorMsg" runat="server">
</asp:literal>
</p>
</form>
</body>
</html>
<%@ page language="VB"%>
<%@ import namespace="System.Net.Mail"%>
<%@ import namespace="System.Reflection"%>
<%@ import namespace="System.Collections.Specialized"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Function ShowMessage(ByVal msg As System.Net.Mail.MailMessage) As HtmlTable
Dim table As HtmlTable = New HtmlTable
Dim topRow As HtmlTableRow = New HtmlTableRow
Dim fieldHeaderCell As HtmlTableCell = New HtmlTableCell
Dim valueHeaderCell As HtmlTableCell = New HtmlTableCell
fieldHeaderCell.InnerText = "Field"
topRow.Cells.Add(fieldHeaderCell)
valueHeaderCell.InnerText = "Value"
topRow.Cells.Add(valueHeaderCell)
table.Rows.Add(topRow)
Dim p As PropertyInfo
For Each p In msg.GetType().GetProperties()
Dim row As HtmlTableRow = New HtmlTableRow
Dim labelCell As HtmlTableCell = New HtmlTableCell
Dim valueCell As HtmlTableCell = New HtmlTableCell
If (Not ((p.Name = "Headers") Or _
(p.Name = "Fields") Or _
(p.Name = "Attachments"))) Then
labelCell.InnerText = String.Format("{0}", p.Name)
row.Cells.Add(labelCell)
valueCell.InnerText = String.Format("{0}", p.GetValue(msg, Nothing))
row.Cells.Add(valueCell)
End If
table.Rows.Add(row)
Next
Return table
End Function
Function CreateMessage() As System.Net.Mail.MailMessage
' <Snippet2>
Dim md As MailDefinition = New MailDefinition
' </Snippet2>
' <Snippet3>
md.BodyFileName = sourceMailFile.Text
' </Snippet3>
' <Snippet4>
md.CC = sourceCC.Text
' </Snippet4>
' <Snippet5>
md.From = sourceFrom.Text
' </Snippet5>
' <Snippet6>
md.Subject = sourceSubject.Text
' </Snippet6>
' <Snippet10>
If sourcePriority.SelectedValue = "Normal" Then
md.Priority = MailPriority.Normal
ElseIf sourcePriority.SelectedValue = "High" Then
md.Priority = MailPriority.High
ElseIf sourcePriority.SelectedValue = "Low" Then
md.Priority = MailPriority.Low
End If
' </Snippet10>
' <Snippet7>
Dim replacements As ListDictionary = New ListDictionary
replacements.Add("<%To%>", sourceTo.Text)
replacements.Add("<%From%>", sourceFrom.Text)
' </Snippet7>
If useFile.Checked Then
' <Snippet8>
Dim fileMsg As System.Net.Mail.MailMessage
fileMsg = md.CreateMailMessage(sourceTo.Text, replacements, Me)
' </Snippet8>
Return fileMsg
Else
' <Snippet9>
Dim textMsg As System.Net.Mail.MailMessage
textMsg = md.CreateMailMessage(sourceTo.Text, replacements, sourceBodyText.Text, Me)
' </Snippet9>
Return textMsg
End If
End Function
Sub createEMail_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim msg As System.Net.Mail.MailMessage = CreateMessage()
PlaceHolder1.Controls.Add(ShowMessage(msg))
End Sub
Sub sendEMail_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim msg As System.Net.Mail.MailMessage = CreateMessage()
PlaceHolder1.Controls.Add(ShowMessage(msg))
Try
Dim sc As SmtpClient
sc = New SmtpClient()
sc.Send(msg)
Catch ex As Exception
errorMsg.Text = ex.ToString()
End Try
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Create an email message</title>
</head>
<body>
<form id="Form1" runat="server">
<table id="Table1" cellspacing="1"
style="padding:1; width:450px; text-align:center">
<tr>
<td align="center" colspan="3">
<h3>Create an email message</h3>
</td>
</tr>
<tr>
<td align="right">To:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceTo" runat="server" columns="54">
</asp:textbox> <asp:requiredfieldvalidator
id="RequiredFieldValidator1" runat="server" errormessage="*"
controltovalidate="sourceTo">
</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
<td align="right">Cc:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceCC" runat="server" columns="54">
</asp:textbox> </td>
</tr>
<tr>
<td align="right">From:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceFrom" runat="server" columns="54">
</asp:textbox> <asp:requiredfieldvalidator
id="RequiredFieldValidator2" runat="server" errormessage="*"
controltovalidate="sourceFrom">
</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
<td align="right">
Priority</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:dropdownlist id="sourcePriority" runat="server">
<asp:listitem value="Low">Low</asp:listitem>
<asp:listitem value="Normal" selected="true">Normal</asp:listitem>
<asp:listitem value="High">High</asp:listitem>
</asp:dropdownlist> </td>
<td>
</td>
</tr>
<tr>
<td align="right">Subject:</td>
<td style="WIDTH: 10px">
</td>
<td>
<asp:textbox id="sourceSubject" runat="server" columns="54">
</asp:textbox> </td>
</tr>
<tr>
<td align="right">Source:</td>
<td style="WIDTH: 10px">
</td>
<td>
<table id="Table2" cellspacing="1" cellpadding="1" width="100%">
<tr>
<td style="WIDTH: 100px">
<asp:radiobutton id="useFile" runat="server"
text="Use file" width="80px" groupname="textSource"
checked="True">
</asp:radiobutton> </td>
<td style="WIDTH: 11px">
</td>
<td>
<p style="text-align:right">File name:</p>
</td>
<td>
<asp:textbox id="sourceMailFile" runat="server" columns="22">
mail.txt</asp:textbox> </td>
</tr>
<tr>
<td style="WIDTH: 100px">
<asp:radiobutton id="useText" runat="server"
text="Enter text" width="80px" height="22px"
groupname="textSource">
</asp:radiobutton> </td>
<td style="WIDTH: 11px">
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</td>
<td> </td>
</tr>
<tr>
<td align="center" colspan="3">
<asp:textbox id="sourceBodyText" runat="server" columns="51"
textmode="MultiLine" rows="15">
</asp:textbox> </td>
</tr>
<tr>
<td align="center" colspan="3">
<asp:button id="createEMail" runat="server"
text="Create email and display only" onclick="createEMail_Click">
</asp:button>
<asp:button id="sendEMail" runat="server" text="Create email and send">
</asp:button></td>
</tr>
</table>
<p> </p>
<p>
<asp:placeholder id="PlaceHolder1" runat="server">
</asp:placeholder> </p>
<p>
<asp:literal id="errorMsg" runat="server">
</asp:literal></p>
</form>
</body>
</html>
Comentários
A MailDefinition classe pode ser usada por controles para criar um MailMessage objeto de um arquivo de texto ou uma cadeia de caracteres que contenha o corpo da mensagem de email.The MailDefinition class can be used by controls to create a MailMessage object from a text file or a string that contains the body of the email message. Use a MailDefinition classe para simplificar a criação de mensagens de email predefinidas para serem enviadas por um controle.Use the MailDefinition class to simplify creating predefined email messages to be sent by a control. Se você quiser enviar emails que não usam um controle, consulte a System.Net.Mail classe.If you want to send email not using a control, see the System.Net.Mail class.
Você pode fazer substituições de texto no corpo da mensagem de email passando para o CreateMailMessage método uma IDictionary instância que mapeia cadeias de caracteres para suas substituições.You can make text substitutions in the body of the email message by passing to the CreateMailMessage method an IDictionary instance that maps strings to their replacements.
O MailMessage objeto criado pela MailDefinition classe é enviado usando o Send método da SmtpClient classe.The MailMessage object created by the MailDefinition class is sent using the Send method of the SmtpClient class. Para poder enviar email, você deve configurar um servidor de email SMTP em seu arquivo de Web.config.To be able to send email, you must configure an SMTP mail server in your Web.config file. Para obter mais informações, consulte o < > elemento SMTP (configurações de rede).For more information, see the <smtp> Element (Network Settings).
Observação
A MailDefinition classe não oferece suporte à associação de dados.The MailDefinition class does not support data binding. As propriedades da MailDefinition classe não podem ser associadas a dados usando a <%# %> sintaxe de expressão de vinculação de dados.Properties of the MailDefinition class cannot be bound to data using the <%# %> data-binding expression syntax.
Construtores
| MailDefinition() |
Inicializa uma nova instância da classe MailDefinition.Initializes a new instance of the MailDefinition class. |
Propriedades
| BodyFileName |
Obtém ou define o nome do arquivo que contém o texto do corpo da mensagem de email.Gets or sets the name of the file that contains text for the body of the email message. |
| CC |
Obtém ou define uma lista separada por vírgulas de endereços de email para a qual enviar uma cópia (CC) da mensagem.Gets or sets a comma-separated list of email addresses to send a copy (CC) of the message to. |
| EmbeddedObjects |
Obtém uma coleção de instâncias EmbeddedMailObject, normalmente usadas para inserir imagens em um objeto MailDefinition antes de enviar um email para um usuário.Gets a collection of EmbeddedMailObject instances, typically used to embed images in a MailDefinition object before sending an email to a user. |
| From |
Obtém ou define o endereço de email do remetente da mensagem.Gets or sets the email address of the message sender. |
| IsBodyHtml |
Obtém ou define um valor que indica se o corpo do email é HTML.Gets or sets a value indicating whether the body of the email is HTML. |
| Priority |
Obtém ou define a prioridade da mensagem de email.Gets or sets the priority of the email message. |
| Subject |
Obtém ou define a linha do assunto da mensagem de email.Gets or sets the subject line of the email message. |
Métodos
| CreateMailMessage(String, IDictionary, Control) |
Cria uma mensagem de email de um arquivo de texto para ser enviada por meio do protocolo SMTP.Creates an email message from a text file to send by means of SMTP (Simple Mail Transfer Protocol). |
| CreateMailMessage(String, IDictionary, String, Control) |
Cria uma mensagem de email com substituições de um arquivo de texto para ser enviada por meio do protocolo SMTP.Creates an email message with replacements from a text file to send by means of SMTP (Simple Mail Transfer Protocol). |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
| IStateManager.IsTrackingViewState |
Obtém um valor que indica se o controle de servidor está salvando alterações no estado de exibição.Gets a value that indicates whether the server control is saving changes to its view state. |
| IStateManager.LoadViewState(Object) |
Restaura informações de estado de exibição de uma solicitação de página anterior salva pelo método SaveViewState().Restores view-state information from a previous page request that was saved by the SaveViewState() method. |
| IStateManager.SaveViewState() |
Salva alterações de estado de exibição do controle de servidor que ocorreram desde a hora em que ocorreu o postback da página no servidor.Saves any server control view-state changes that have occurred since the time the page was posted back to the server. |
| IStateManager.TrackViewState() |
Causa o acompanhamento das alterações de estado de exibição para o controle de servidor, para que elas possam ser armazenadas no objeto StateBag do controle de servidor.Causes tracking of view-state changes to the server control so they can be stored in the server control's StateBag object. |