sábado, 12 de outubro de 2013

Enviando E-mail com C#

Galerinha, vou explicar como enviar e-mails utilizando nosso amigo C-Sharp. A ideia deste artigo é enviar e-mails atraves do Outlook efetuando a leitura dos e-mails em um banco de dados, por tanto vamos utilizar as seguintes ações:



  • Form em C#;
  • Banco de dados;
  • Outlook para disparar os e-mails;
 Crie um arquivo App.config para configurar o banco de dados:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="AccessConnectionString"
      connectionString="Data Source=xxx.xxx.xxx.xxx; Integrated Security=SSPI;" />
  </connectionStrings>
</configuration>

Para disparar os emails vamos clicar um Class chamada:Email.cs

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EnviaEmail.Mail
{
    public class Email
    {
        public string Subject
        {
            get { return this.subject; }
            set { this.subject = value; }
        }
        private string subject;

        public List<string> To
        {
            get { return this.to; }
        }
        private List<string> to;

        public List<string> Copy
        {
            get { return this.copy; }
        }
        private List<string> copy;

        public List<string> Attachs
        {
            get { return this.attachs; }
        }
        private List<string> attachs;

        public string Body
        {
            get { return this.body; }
            set { this.body = value; }
        }
        private string body;

        public Email()
        {
            this.subject = "";
            this.to = new List<string>();
            this.copy = new List<string>();
            this.attachs = new List<string>();
            this.body = "";
        }

        public void LoadBodyFromFile(string pFile)
        {
            string tmp = "";

            string[] file = System.IO.File.ReadAllLines(pFile);
            for (int i = 0; i < file.Length; i++)
                tmp += file[i];

            this.body = tmp;
        }

        public void Open()
        {
            this.Execute(false);
        }

        public void Send()
        {
            this.Execute(true);
        }

        private void Execute(bool pDirectlySend)
        {
            try
            {
                // Instancia outlook e cria e-mail em branco //
                Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook._MailItem oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

                // Organiza endereços de destino //
                string to = "";
                foreach (string email in this.To)
                    to += email + ";";
                if (to.Length > 0)
                    oMailItem.To = to.Substring(0, to.Length - 1);

                string copy = "";
                foreach (string email in this.Copy)
                    copy += email + ";";
                if (copy.Length > 0)
                    oMailItem.CC = copy.Substring(0, copy.Length - 1);

                // Seta assunto
                oMailItem.Subject = this.Subject;

                if (this.Body.ToLower().Substring(0, (this.Body.Length < 100 ? this.Body.Length : 100)).Contains("<html>"))
                {
                    // Seta formato HTML e corpo do e-mail //
                    oMailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
                    oMailItem.HTMLBody = this.Body;
                }
                else
                {
                    // Seta formato RichText e corpo do e-mail //
                    oMailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
                    oMailItem.Body = this.Body;
                }

                // Adiciona anexos //
                for (int i = 0; i < this.Attachs.Count; i++)
                    if (System.IO.File.Exists(this.Attachs[i]))
                        oMailItem.Attachments.Add(
                            this.Attachs[i],
                            Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue,
                            i + 1,
                            this.Attachs[i].Split('\\')[this.Attachs[i].Split('\\').Length - 1]
                        );

                if (!pDirectlySend)
                {
                    // Abre email //
                    string name;
                    do
                    {
                        name = "msg." + new Random().Next() + ".msg";
                    } while (System.IO.File.Exists("C:\\temp\\" + name));

                    oMailItem.SaveAs("C:\\temp\\" + name, Microsoft.Office.Interop.Outlook.OlSaveAsType.olMSG);

                    // Abre o  e-mail criado //
                    System.Diagnostics.Process prcs = new System.Diagnostics.Process();
                    prcs.StartInfo.FileName = "\"C:\\temp\\" + name + "\"";
                    prcs.Start();
                    prcs.Dispose();
                }
                else
                    // Envia o e-mail //
                    oMailItem.Send();
            }
            catch (Exception ex)
            {
                string erro;
                erro = ex.Message.ToString();
            }
        }
    }
}


Agora que já temos nossa Class de disparo e configuração do e-mail, precisamos chama-la, no Form1.cs veja o código:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EnviaEmail.Mail;
using System.Data.SqlClient;
using System.Configuration;
using Web.CryptQueryString;
using System.Timers;


namespace EnviaEmail
{
    public partial class Form1 : Form
    {
        int i = 0, TotRow;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Timers.Timer timerMoveSprite;
            timerMoveSprite = new System.Timers.Timer(); // Inicializa
            timerMoveSprite.Interval = 20000; // Define Intervalo em Milisegundos
            timerMoveSprite.Elapsed += new ElapsedEventHandler(MoveSprite); // Adiciona a função que criamos na lista de funções a serem chamadas quando o intervalo for atingido
            timerMoveSprite.Start(); // Ativa o Timer (faz o mesmo começar a contagem)
        }

        public void EnviarMail()
        {
            if (cbEmailsSistema.Checked == true)
            {
                //Conexão
                string strConn = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ToString();
                SqlConnection conn = new SqlConnection(strConn);
                //Consulta no banco de dados
                string strSql = "SELECT DE,PARA,LAYOUT,DEMANDA,NOME,ENVIADO,DTCRIADO,DTENVIADO,OUTROS,DESCRICAO FROM Processos.dbo.tblEmail WHERE ENVIADO = 'NÃO'";

                conn.Open();
                SqlCommand cmd = new SqlCommand(strSql, conn);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                conn.Close();

                if (dt.Rows.Count >= 1)
                {
                    Email SendMail = new Email();
                    TotRow = dt.Rows.Count;
                    i = 0;

                    while (i < TotRow)
                    {
                        #region Sistema WebCash

                        #region Layout 0 - Envia Email
                        if (dt.Rows[i]["LAYOUT"].ToString() == "0")
                        {

                            SendMail.To.Clear();
                            SendMail.To.Add(dt.Rows[i]["PARA"].ToString());
                            SendMail.Subject = "titulo";
                            string menssagem = dt.Rows[i]["DESCRICAO"].ToString() + System.Environment.NewLine + System.Environment.NewLine;
                            menssagem = menssagem + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine;
                            menssagem = menssagem + "Obs. Este e-mail é automático, favor não responder." + System.Environment.NewLine;

                            SendMail.Body = menssagem.ToString();

                            SendMail.Send();

                            conn.Open();
                            string strSql2 = "UPDATE Processos.dbo.tblEmail SET ENVIADO = 'SIM', DTENVIADO = CONVERT(NVARCHAR(10),GETDATE(),103) WHERE DEMANDA = '" + dt.Rows[i]["DEMANDA"].ToString() + "'";
                            SqlCommand cmd2 = new SqlCommand(strSql2, conn);
                            cmd2.ExecuteNonQuery();
                            conn.Close();

                        }
                        #endregion

                        #endregion

                        ++i;
                    }
                    TotRow = 0;
                }
            }
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                Show();
                WindowState = FormWindowState.Normal;
            }
        }

        private void Form1_Resize_1(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                Hide();
            }
        }

         public void MoveSprite(object source, ElapsedEventArgs e)
        {
            EnviarMail();
        }
    }
}


 Para baixar o código fonte, clique aqui

0 comentários:

Postar um comentário