Pergunta

Estou enviando MailMessages com um SMTPClient (sendo entregue com sucesso) usando um servidor Exchange, mas gostaria que meus e -mails enviados fossem para a pasta enviada do endereço de e -mail que estou enviando (não estou acontecendo).

using (var mailMessage = new MailMessage("fromaddress@blah.com", "toaddress@blah.com", "subject", "body"))
{
    var smtpClient = new SmtpClient("SmtpHost")
    {
        EnableSsl = false,
        DeliveryMethod = SmtpDeliveryMethod.Network
    };

    // Apply credentials
    smtpClient.Credentials = new NetworkCredential("smtpUsername", "smtpPassword");

    // Send
    smtpClient.Send(mailMessage);
}

Existe uma configuração que estou perdendo que garantirá todos os meus e -mails enviados de "Fromaddress@blah.com" chegar à pasta enviada?

Foi útil?

Solução

Suponho que sua exigência seja orientada principalmente para dar aos usuários visibilidade para quais e -mails foram enviados. A pasta de itens enviados seria um método para permitir que isso ocorra. No passado, eu resolvi esse problema adicionando um BCC Address Isso literalmente enviaria o email diretamente para uma lista de distribuição, usuário ou caixa de correio compartilhada que permitia aos usuários revisar o que havia sido enviado.

Experimente isso com uma regra de perspectiva de algum tipo para mover o item para a pasta de itens enviados marcados como lida ...

using (var mailMessage = new MailMessage(
        "fromaddress@blah.com", 
        "toaddress@blah.com", 
        "",
        "fromaddress@blah.com",
        "subject", 
        "body"))
{
    var smtpClient = new SmtpClient("SmtpHost")
    {
        EnableSsl = false,
        DeliveryMethod = SmtpDeliveryMethod.Network
    };

    // Apply credentials
    smtpClient.Credentials = new NetworkCredential("smtpUsername", "smtpPassword");

    // Send
    smtpClient.Send(mailMessage);
}

Outras dicas

Eu fiz isso, então, para completar, aqui está como fazê -lo corretamente. Usando o serviço da Web do Exchange Managed ( http://msdn.microsoft.com/en-us/library/dd633709%28exchg.80%29.aspx ):

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

// In case you have a dodgy SSL certificate:
System.Net.ServicePointManager.ServerCertificateValidationCallback =
            delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                return true;
            };

service.Credentials = new WebCredentials("username", "password", "MYDOMAIN");
service.Url = new Uri("https://exchangebox/EWS/Exchange.asmx");

EmailMessage em = new EmailMessage(service);
em.Subject = "example email";
em.Body = new MessageBody("hello world");
em.Sender = new Microsoft.Exchange.WebServices.Data.EmailAddress("john.smith@example.com");
em.ToRecipients.Add(new Microsoft.Exchange.WebServices.Data.EmailAddress("bob.smith@example.com"));

// Send the email and put it into the SentItems:
em.SendAndSaveCopy(WellKnownFolderName.SentItems);

Você precisa enviar a mensagem do Outlook se deseja ter a mensagem enviada na pasta "Mensagens enviadas". Esta pasta é um conceito de perspectiva (e muitos outros clientes de email), não um conceito SMTP.

Você pode usar a API de automação do Outlook para pedir ao Outlook para criar um e-mail e enviá-lo.

Eu tenho procurado uma resposta a essa pergunta, mas sem confiar em um servidor Exchange e, em vez disso, usar um servidor IMAP. Não sei se isso cai do escopo da pergunta, mas achei que ele está procurando "obter uma magia enviada para a pasta enviada", que era o meu problema em primeiro lugar.

Não encontrei uma resposta direta em nenhum lugar em que construí minha própria solução com base:

Estou implementando o método de salvamento como uma extensão para smtpclient para que, em vez de .Send() Estaremos usando .SendAndSaveMessageToIMAP().

public static class SmtpClientExtensions
{
    static System.IO.StreamWriter sw = null;
    static System.Net.Sockets.TcpClient tcpc = null;
    static System.Net.Security.SslStream ssl = null;
    static string path;
    static int bytes = -1;
    static byte[] buffer;
    static System.Text.StringBuilder sb = new System.Text.StringBuilder();
    static byte[] dummy;

    /// <summary>
    /// Communication with server
    /// </summary>
    /// <param name="command">The command beeing sent</param>
    private static void SendCommandAndReceiveResponse(string command)
    {
        try
        {
            if (command != "")
            {
                if (tcpc.Connected)
                {
                    dummy = System.Text.Encoding.ASCII.GetBytes(command);
                    ssl.Write(dummy, 0, dummy.Length);
                }
                else
                {
                    throw new System.ApplicationException("TCP CONNECTION DISCONNECTED");
                }
            }
            ssl.Flush();

            buffer = new byte[2048];
            bytes = ssl.Read(buffer, 0, 2048);
            sb.Append(System.Text.Encoding.ASCII.GetString(buffer));

            sw.WriteLine(sb.ToString());
            sb = new System.Text.StringBuilder();
        }
        catch (System.Exception ex)
        {
            throw new System.ApplicationException(ex.Message);
        }
    }

    /// <summary>
    /// Saving a mail message before beeing sent by the SMTP client
    /// </summary>
    /// <param name="self">The caller</param>
    /// <param name="imapServer">The address of the IMAP server</param>
    /// <param name="imapPort">The port of the IMAP server</param>
    /// <param name="userName">The username to log on to the IMAP server</param>
    /// <param name="password">The password to log on to the IMAP server</param>
    /// <param name="sentFolderName">The name of the folder where the message will be saved</param>
    /// <param name="mailMessage">The message being saved</param>
    public static void SendAndSaveMessageToIMAP(this System.Net.Mail.SmtpClient self, System.Net.Mail.MailMessage mailMessage, string imapServer, int imapPort, string userName, string password, string sentFolderName)
    {
        try
        {
            path = System.Environment.CurrentDirectory + "\\emailresponse.txt";

            if (System.IO.File.Exists(path))
                System.IO.File.Delete(path);

            sw = new System.IO.StreamWriter(System.IO.File.Create(path));

            tcpc = new System.Net.Sockets.TcpClient(imapServer, imapPort);

            ssl = new System.Net.Security.SslStream(tcpc.GetStream());
            ssl.AuthenticateAsClient(imapServer);
            SendCommandAndReceiveResponse("");

            SendCommandAndReceiveResponse(string.Format("$ LOGIN {1} {2}  {0}", System.Environment.NewLine, userName, password));

            using (var m = mailMessage.RawMessage())
            {
                m.Position = 0;
                var sr = new System.IO.StreamReader(m);
                var myStr = sr.ReadToEnd();
                SendCommandAndReceiveResponse(string.Format("$ APPEND {1} (\\Seen) {{{2}}}{0}", System.Environment.NewLine, sentFolderName, myStr.Length));
                SendCommandAndReceiveResponse(string.Format("{1}{0}", System.Environment.NewLine, myStr));
            }
            SendCommandAndReceiveResponse(string.Format("$ LOGOUT{0}", System.Environment.NewLine));
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("error: " + ex.Message);
        }
        finally
        {
            if (sw != null)
            {
                sw.Close();
                sw.Dispose();
            }
            if (ssl != null)
            {
                ssl.Close();
                ssl.Dispose();
            }
            if (tcpc != null)
            {
                tcpc.Close();
            }
        }

        self.Send(mailMessage);
    }
}
public static class MailMessageExtensions
{
    private static readonly System.Reflection.BindingFlags Flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
    private static readonly System.Type MailWriter = typeof(System.Net.Mail.SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter");
    private static readonly System.Reflection.ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(Flags, null, new[] { typeof(System.IO.Stream) }, null);
    private static readonly System.Reflection.MethodInfo CloseMethod = MailWriter.GetMethod("Close", Flags);
    private static readonly System.Reflection.MethodInfo SendMethod = typeof(System.Net.Mail.MailMessage).GetMethod("Send", Flags);

    /// <summary>
    /// A little hack to determine the number of parameters that we
    /// need to pass to the SaveMethod.
    /// </summary>
    private static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3;

    /// <summary>
    /// The raw contents of this MailMessage as a MemoryStream.
    /// </summary>
    /// <param name="self">The caller.</param>
    /// <returns>A MemoryStream with the raw contents of this MailMessage.</returns>
    public static System.IO.MemoryStream RawMessage(this System.Net.Mail.MailMessage self)
    {
        var result = new System.IO.MemoryStream();
        var mailWriter = MailWriterConstructor.Invoke(new object[] { result });
        SendMethod.Invoke(self, Flags, null, IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null);
        result = new System.IO.MemoryStream(result.ToArray());
        CloseMethod.Invoke(mailWriter, Flags, null, new object[] { }, null);
        return result;
    }
}

Então o exemplo de Robert Reid se tornaria

        using (var mailMessage = new MailMessage("fromaddress@blah.com", "toaddress@blah.com", "subject", "body"))
        {
            //Add an attachment just for the sake of it
            Attachment doc = new Attachment(@"filePath");
            doc.ContentId = "doc";
            mailMessage.Attachments.Add(doc);

            var smtpClient = new SmtpClient("SmtpHost")
            {
                EnableSsl = false,
                DeliveryMethod = SmtpDeliveryMethod.Network
            };

            // Apply credentials
            smtpClient.Credentials = new NetworkCredential("smtpUsername", "smtpPassword");

            // Send
            smtpClient.SendAndSaveMessageToIMAP(mailMessage, "imap.mail.com", 993, "imapUsername", "imapPassword", "SENT");
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top