Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
0 de 1 pessoas classificaram isso como útil - Avalie este tópico

SmtpClient Classe

Permite que aplicativos enviem e-mail usando o protocolo Simple Mail Transfer Protocol (SMTP).

Namespace:  System.Net.Mail
Assembly:  System (em System. dll)
public class SmtpClient

The SmtpClient class is used to send e-mail to an SMTP server for delivery.The classes shown in the following table are used to construct e-mail messages that can be sent using SmtpClient.

Classe

Descrição

Attachment

Anexos de arquivo representa.Esta classe permite anexar arquivos, fluxos ou texto a uma mensagem de email.

MailAddress

Representa o endereço de email do remetente e os destinatários.

MailMessage

Representa uma mensagem de email.

To construct and send an e-mail message by using SmtpClient, you must specify the following information:

  • O servidor host SMTP que você usa para enviar email.See the Host and Port[properties].

  • Credenciais para autenticação, se exigido pelo servidor SMTP.See the Credentials property.

  • O endereço de email do remetente.See the Send and SendAsync methods that take a from parameter.Also see the MailMessage.From property.

  • O endereço de email ou endereços de destinatários.See the Send and SendAsync methods that take a recipient parameter.Also see the MailMessage.To property.

  • O conteúdo da mensagem.See the Send and SendAsync methods that take a body parameter.Also see the MailMessage.Body property.

To include an attachment with an e-mail message, first create the attachment by using the Attachment class, and then add it to the message by using the MailMessage.Attachments property.Dependendo o leitor de email usado pelos destinatários e o tipo de arquivo do anexo, alguns destinatários talvez não consiga ler o anexo.For clients that cannot display the attachment in its original form, you can specify alternate views by using the MailMessage.AlternateViews property.

You can use the application or machine configuration files to specify default host, port, and credentials values for all SmtpClient objects.Para obter mais informações, consulte < mailSettings > elemento (Configurações Network).

To send the e-mail message and block while waiting for the e-mail to be transmitted to the SMTP server, use one of the synchronous Send methods.To allow your program's main thread to continue executing while the e-mail is transmitted, use one of the asynchronous SendAsync methods.The SendCompleted event is raised when a SendAsync operation completes.To receive this event, you must add a SendCompletedEventHandler delegate to SendCompleted.The SendCompletedEventHandler delegate must reference a callback method that handles notification of SendCompleted events.To cancel an asynchronous e-mail transmission, use the SendAsyncCancel method.

ObservaçãoObservação:

If there is an e-mail transmission in progress and you call SendAsync or Send again, you will receive an InvalidOperationException.

SMTP is defined in RFC 2821, which is available at http://www.ietf.org.

O exemplo de código a seguir demonstra enviar uma mensagem de email de forma assíncrona.


using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.Async
{
    public class SimpleAsynchronousExample
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
             String token = (string) e.UserState;

            if (e.Cancelled)
            {
                 Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                 Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            } else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
        public static void Main(string[] args)
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("jane@contoso.com", 
               "Jane " + (char)0xD8+ " Clayton", 
            System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress("ben@contoso.com");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding =  System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new 
            SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback 
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";
            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();
            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
    }
}


System.Object
  System.Net.Mail.SmtpClient
Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.
Isso foi útil para você?
(1500 caracteres restantes)

Contribuições da comunidade

ADICIONAR
A Microsoft está realizando uma pesquisa online para saber sua opinião sobre o site do MSDN. Se você optar por participar, a pesquisa online lhe será apresentada quando você sair do site do MSDN.

Deseja participar?
© 2013 Microsoft. Todos os direitos reservados.