Esempio n. 1
0
        public override Server creack(String ip, int port, String username, String password, int timeOut)
        {
            SMTP_Client conn   = null;
            Server      server = new Server();

            try
            {
                conn         = new SMTP_Client();
                conn.Timeout = timeOut;
                conn.Connect(ip, port, false);
                if (conn.IsConnected)
                {
                    conn.EhloHelo(ip);
                    AUTH_SASL_Client_Plain authInfo = new AUTH_SASL_Client_Plain(username, password);
                    conn.Auth(authInfo);
                    if (conn.IsAuthenticated)
                    {
                        server.isSuccess = conn.IsAuthenticated;
                        server.banner    = conn.GreetingText;
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Disconnect();
                }
            }
            return(server);
        }
Esempio n. 2
0
        public bool Authenticate()
        {
            var musername = mSMTPUsername;

            if (mSMTPUsername != null && mSMTPUsername.IndexOf("@") >= 0)
            {
                musername = mSMTPUsername.Substring(0, mSMTPUsername.IndexOf("@"));
            }

            using (SMTP_Client client = new SMTP_Client())
            {
                try
                {
                    client.Connect(mSMTPServer, mSMTPPort);
                    client.EhloHelo(mSMTPServer);

                    client.Authenticate(musername, mSMTPPassword);

                    return(client.IsAuthenticated);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    client.Disconnect();
                }
            }
        }
Esempio n. 3
0
 public void CreateHost(ConfigHost host)
 {
     Host = new SMTP_Client();
     Host.Connect(host.Server, host.Port, host.EnableSsl);
     Host.EhloHelo(host.Server);
     Host.Auth(Host.AuthGetStrongestMethod(host.Username, host.Password));
 }
        /// <summary>
        /// Smart host relay session constructor.
        /// </summary>
        /// <param name="server">Owner relay server.</param>
        /// <param name="realyItem">Relay item.</param>
        /// <param name="smartHosts">Smart hosts.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>realyItem</b> or <b>smartHosts</b>is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        internal Relay_Session(Relay_Server server, Relay_QueueItem realyItem, Relay_SmartHost[] smartHosts)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (realyItem == null)
            {
                throw new ArgumentNullException("realyItem");
            }
            if (smartHosts == null)
            {
                throw new ArgumentNullException("smartHosts");
            }

            m_pServer     = server;
            m_pRelayItem  = realyItem;
            m_pSmartHosts = smartHosts;

            m_RelayMode         = Relay_Mode.SmartHost;
            m_SessionID         = Guid.NewGuid().ToString();
            m_SessionCreateTime = DateTime.Now;
            m_pTargets          = new List <Relay_Target>();
            m_pSmtpClient       = new SMTP_Client();
        }
Esempio n. 5
0
        /// <summary>
        /// Dns relay session constructor.
        /// </summary>
        /// <param name="server">Owner relay server.</param>
        /// <param name="localBindInfo">Local bind info.</param>
        /// <param name="realyItem">Relay item.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>server</b>,<b>localBindInfo</b> or <b>realyItem</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        internal Relay_Session(Relay_Server server, IPBindInfo localBindInfo, Relay_QueueItem realyItem)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (localBindInfo == null)
            {
                throw new ArgumentNullException("localBindInfo");
            }
            if (realyItem == null)
            {
                throw new ArgumentNullException("realyItem");
            }

            m_pServer        = server;
            m_pLocalBindInfo = localBindInfo;
            m_pRelayItem     = realyItem;

            m_SessionID         = Guid.NewGuid().ToString();
            m_SessionCreateTime = DateTime.Now;
            m_pTargets          = new List <Relay_Target>();
            m_pSmtpClient       = new SMTP_Client();

            m_pSmtpClient.BdatEnabled = false;
        }
Esempio n. 6
0
 /// <summary>
 /// 发送邮件
 /// </summary>
 /// <param name="smtp">Smtp对象</param>
 /// <param name="_strRcpTo">收件地址</param>
 /// <param name="mimeStreams">内存流</param>
 private void SendMail(SMTP_Client smtp, string _strRcpTo, MemoryStream mimeStreams)
 {
     smtp.Connect(this.Smtp, WellKnownPorts.SMTP);
     smtp.EhloHelo(this.Smtp);
     smtp.Authenticate(this.Account, this.CurrentUserMailPassWord);
     smtp.MailFrom(this.CurrentUserMail, -1);
     smtp.RcptTo(_strRcpTo);
     mimeStreams.Position = 0;
     smtp.SendMessage(mimeStreams);
     smtp.Disconnect();
 }
Esempio n. 7
0
        /// <summary>
        /// Start processing relay message.
        /// </summary>
        /// <param name="state">User data.</param>
        internal void Start(object state)
        {
            try{
                m_pSmtpClient = new SMTP_Client();
                m_pSmtpClient.LocalHostName = m_pLocalBindInfo.HostName;
                if (m_pServer.Logger != null)
                {
                    m_pSmtpClient.Logger           = new Logger();
                    m_pSmtpClient.Logger.WriteLog += new EventHandler <WriteLogEventArgs>(SmtpClient_WriteLog);
                }

                LogText("Starting to relay message '" + m_pRelayItem.MessageID + "' from '" + m_pRelayItem.From + "' to '" + m_pRelayItem.To + "'.");

                // Get all possible target hosts for active recipient.
                List <string> targetHosts = new List <string>();
                if (m_RelayMode == Relay_Mode.Dns)
                {
                    foreach (string host in SMTP_Client.GetDomainHosts(m_pRelayItem.To))
                    {
                        try{
                            foreach (IPAddress ip in Dns_Client.Resolve(host))
                            {
                                m_pTargets.Add(new Relay_Target(new IPEndPoint(ip, 25)));
                            }
                        }
                        catch {
                            // Failed to resolve host name.

                            LogText("Failed to resolve host '" + host + "' name.");
                        }
                    }
                }
                else if (m_RelayMode == Relay_Mode.SmartHost)
                {
                    foreach (Relay_SmartHost smartHost in m_pSmartHosts)
                    {
                        try{
                            m_pTargets.Add(new Relay_Target(new IPEndPoint(Dns_Client.Resolve(smartHost.Host)[0], smartHost.Port), smartHost.SslMode, smartHost.UserName, smartHost.Password));
                        }
                        catch {
                            // Failed to resolve smart host name.

                            LogText("Failed to resolve smart host '" + smartHost.Host + "' name.");
                        }
                    }
                }

                BeginConnect();
            }
            catch (Exception x) {
                Dispose(x);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        public void SendMail()
        {
            //为发件构造邮件内存流
            MemoryStream mimeStreams = this.MemoryStreamMime();
            Mime         myMime      = this.MakeMime();

            try
            {
                using (SMTP_Client smtp = new SMTP_Client())
                {
                    LumiSoftSendMailBaseArgs e = OnSendMailing(this.Account, this.CurrentUserMail, this.To, this.CC, this.BCC, myMime, mimeStreams);
                    if (!e.IsCancel)
                    {
                        //To:
                        string[] _ArrayTo = this.To.Split(';');
                        foreach (string _str_each_to in _ArrayTo)
                        {
                            if (_str_each_to.Trim() != "")
                            {
                                this.SendMail(smtp, _str_each_to, mimeStreams);
                            }
                        }
                        //CC:
                        string[] _ArrayCC = this.CC.Split(';');
                        foreach (string _str_each_cc in _ArrayCC)
                        {
                            if (_str_each_cc.Trim() != "")
                            {
                                this.SendMail(smtp, _str_each_cc, mimeStreams);
                            }
                        }
                        //BCC:
                        string[] _ArrayBCC = this.BCC.Split(';');
                        foreach (string _str_each_bcc in _ArrayBCC)
                        {
                            if (_str_each_bcc.Trim() != "")
                            {
                                this.SendMail(smtp, _str_each_bcc, mimeStreams);
                            }
                        }
                        OnSendMailSuccessed(this.Account, this.CurrentUserMail, this.To, this.CC, this.BCC, myMime, mimeStreams);
                    }
                }
            }
            catch (Exception ex)
            {
                OnSendMailError(this.Account, this.CurrentUserMail, this.To, this.CC, this.BCC, myMime, mimeStreams, ex);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Completes relay session and does clean up. This method is thread-safe.
        /// </summary>
        /// <param name="exception">Exception happened or null if relay completed successfully.</param>
        public void Dispose(Exception exception)
        {
            try
            {
                lock (this)
                {
                    if (m_IsDisposed)
                    {
                        return;
                    }
                    try
                    {
                        m_pServer.OnSessionCompleted(this, exception);
                    }
                    catch
                    {
                    }
                    m_pServer.Sessions.Remove(this);
                    m_IsDisposed = true;

                    m_pLocalBindInfo = null;
                    m_pRelayItem     = null;
                    m_pSmartHosts    = null;
                    if (m_pSmtpClient != null)
                    {
                        m_pSmtpClient.Dispose();
                        m_pSmtpClient = null;
                    }
                    m_pTargets = null;
                    if (m_pActiveTarget != null)
                    {
                        m_pServer.RemoveIpUsage(m_pActiveTarget.Target.Address);
                        m_pActiveTarget = null;
                    }
                    m_pServer = null;
                }
            }
            catch (Exception x)
            {
                if (m_pServer != null)
                {
                    m_pServer.OnError(x);
                }
            }
        }
Esempio n. 10
0
        public void SendEmail(Mail mail, Setting setting)
        {
            Mail_Message message = new Mail_Message()
            {
                From      = new Mail_t_MailboxList(),
                Subject   = mail.Subject,             //增加主题
                Priority  = mail.Priority.ToString(), //设置优先级
                MessageID = MIME_Utils.CreateMessageID(),
                Date      = mail.CreatedDateTime
            };

            //增加发件人地址
            message.From.Add(new Mail_t_Mailbox(null, mail.From));
            //增加收件人地址
            mail.To.ForEach(address => message.To.Add(new Mail_t_Mailbox(address, address)));

            //增加邮件内容
            MIME_Entity.CreateEntity_Text_Html("Base64", Encoding.Default, mail.Body);

            //增加附件
            if (mail.Attachments != null && mail.Attachments.Count > 0)
            {
                mail.Attachments.ForEach(attachment =>
                {
                    MIME_Entity.CreateEntity_Attachment(attachment.Name);
                });
            }

            using (SMTP_Client smtpClient = new SMTP_Client())
            {
                //设置SMPT服务地址和端口并连接
                smtpClient.Connect(setting.SmtpHostName, setting.SmtpPort);
                //设置Authentication
                smtpClient.Auth(new LumiSoft.Net.AUTH.AUTH_SASL_Client_Login(setting.User.UserName, setting.User.Password));

                using (MemoryStream stream = new MemoryStream())
                {
                    message.ToStream(stream);
                    stream.Position = 0;
                    //发送邮件
                    smtpClient.SendMessage(stream);
                }
            }
        }
Esempio n. 11
0
        public static void Main()
        {
            // By defining the CORRECT! date, mail messages could get a lower spam score in spam filters
            //Utility.SetLocalTime(new DateTime(2012, 1, 26, 20, 43, 0, 0));

            // Defines the sender
            SMTP_Client.MailContact From = new SMTP_Client.MailContact("administrator@localhost", "Your name");
            // Defines the receiver
            SMTP_Client.MailContact Receiver = new SMTP_Client.MailContact("someone@else", "Recipients name");
            // Defines the mail message
            SMTP_Client.MailMessage Message = new SMTP_Client.MailMessage("Small test result");
            Message.Body  = "This mail is sent by a Netduino :-)\r\n";
            Message.Body += "Good day!";

            // Initializes the mail sender class (When your ISP blocks port 25, try 587. A lot of SMTP servers respond to that as well!)
            SMTP_Client Sender = new SMTP_Client(new IntegratedSocket("smtp.yourisp.com", 25));

            // Sends the mail
            Sender.Send(Message, From, Receiver);
        }
Esempio n. 12
0
        /// <summary>
        /// 调用lumisoft发送邮件
        /// </summary>
        /// <param name="fromEmailAddr">发送者的邮件地址</param>
        /// <param name="toEmailAddr">给谁发的邮件地址</param>
        /// <param name="subjectText">主题</param>
        /// <param name="bodyText">正文</param>
        /// <param name="filePath">附件路径</param>
        /// <returns>成功与否</returns>
        public static bool SendMailByLumisoft(string fromEmailAddr, string toEmailAddr, string subjectText, string bodyText, string filePath)
        {
            Mime       m          = new Mime();
            MimeEntity mainEntity = m.MainEntity;

            // Force to create From: header field
            mainEntity.From = new AddressList();
            mainEntity.From.Add(new MailboxAddress(fromEmailAddr, fromEmailAddr));
            // Force to create To: header field
            mainEntity.To = new AddressList();
            mainEntity.To.Add(new MailboxAddress(toEmailAddr, toEmailAddr));
            mainEntity.Subject = subjectText;
            //添加正文
            mainEntity.ContentType = MediaType_enum.Multipart_mixed;
            MimeEntity textEntity = mainEntity.ChildEntities.Add();

            textEntity.ContentType             = MediaType_enum.Text_html;
            textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64;
            textEntity.DataText = bodyText;
            //发送附件
            if (!string.IsNullOrEmpty(filePath))
            {
                MimeEntity attachmentEntity = new MimeEntity();
                attachmentEntity.ContentType                 = MediaType_enum.Application_octet_stream;
                attachmentEntity.ContentDisposition          = ContentDisposition_enum.Attachment;
                attachmentEntity.ContentTransferEncoding     = ContentTransferEncoding_enum.Base64;
                attachmentEntity.ContentDisposition_FileName = filePath;
                attachmentEntity.DataFromFile(filePath);
                mainEntity.ChildEntities.Add(attachmentEntity);
            }
            try
            {
                SMTP_Client.QuickSend(m);
                return(true);
            }
            catch (Exception e)
            {
                //Console.Write(e.StackTrace);
                return(false);
            }
        }
Esempio n. 13
0
        public static bool SendMail(string Body, string Title, string reciveEmail)
        {
            bool sended = false;

            using (SMTP_Client client = new SMTP_Client())
            {
                try
                {
                    //与Pop3服务器建立连接
                    client.Connect(smtp, port, false);
                    client.EhloHelo(smtp);
                    //验证身份
                    var authhh = new AUTH_SASL_Client_Plain(sendEmail, sendPassword);
                    client.Auth(authhh);
                    client.MailFrom(sendEmail, -1);
                    //收件人列表
                    client.RcptTo(reciveEmail);
                    //采用Mail_Message类型的Stream
                    Mail_Message m = Create_PlainText_Html_Attachment_Image(reciveEmail, sendEmail, sendEmail, Title, Body);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        m.ToStream(stream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);
                        stream.Position = 0;
                        client.SendMessage(stream);
                        sended = true;
                    }
                    if (m != null)
                    {
                        m.Dispose();
                    }
                    client.Disconnect();
                    client.Dispose();
                }
                catch {
                    return(false);
                }
            }
            return(sended);
        }
Esempio n. 14
0
        private static void startDelivery()
        {
            DirectoryInfo curdir = new DirectoryInfo(System.Environment.CurrentDirectory + @"\INBOUND\");

            FileInfo[] fileEntries = curdir.GetFiles("*.eml");

            //string[] fileEntries = Directory.GetFiles(System.Environment.CurrentDirectory + @"\INBOUND\","*.eml");
            foreach (FileInfo fileName in fileEntries)
            {
                DefaultLogger.Log.LogDebug("Filename: " + fileName.FullName);

                var eml = MsgReader.Mime.Message.Load(fileName);


                if (eml.Headers != null)
                {
                    if (eml.Headers.To != null)
                    {
                        foreach (var recipient in eml.Headers.To)
                        {
                            var to = recipient.Address;
                            DefaultLogger.Log.LogDebug("Mail to: " + to);

                            using (FileStream fs = new FileStream(fileName.FullName, FileMode.Open, FileAccess.Read))
                                using (LumiSoft.Net.SMTP.Client.SMTP_Client client =
                                           new LumiSoft.Net.SMTP.Client.SMTP_Client())
                                {
                                    var message = LumiSoft.Net.Mail.Mail_Message.ParseFromFile(fileName.FullName);


                                    //SMTP_Client.QuickSendSmartHost("localhost", "192.168.1.216", 25, false, "fakeuser", "fakepassword", message);
                                    SMTP_Client.QuickSendSmartHost("192.168.1.216", 26, false, message);
                                }
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        private Boolean SendMailNew(bool isAsync, object userState)
        {
            string[] mailTos  = mMailTo;
            string[] mailCcs  = mMailCc;
            string[] mailBccs = mMailBcc;
            Dictionary <string, string> attachments = mMailAttachments;

            var toList = new Dictionary <string, string>();

            foreach (var to in MailTo)
            {
                toList.Add(to, to);
            }

            var musername = mSMTPUsername;

            if (mSMTPUsername != null && mSMTPUsername.IndexOf("@") >= 0)
            {
                musername = mSMTPUsername.Substring(0, mSMTPUsername.IndexOf("@"));
            }

            bool checkspmail = CheckSpecialMail(toList);

            if (!checkspmail && MailCc != null)
            {
                checkspmail = CheckSpecialMail(MailCc);
            }
            if (checkspmail)
            {
                foreach (string address in toList.Keys)
                {
                    using (SMTP_Client client = new SMTP_Client())
                    {
                        client.Timeout = this.Timeout;
                        client.Connect(mSMTPServer, mSMTPPort);
                        client.EhloHelo(mSMTPServer);


                        client.Authenticate(musername, mSMTPPassword);
                        client.MailFrom(mMailFrom, -1);
                        client.RcptTo(address);


                        Mail_Message m = Create_PlainText_Html_Attachment_Image(toList, new Dictionary <string, string>()
                                                                                , mMailFrom,
                                                                                mMailFrom, MailSubject, mMailBody, attachments, "", "", CheckSpecialMail(new string[] { address }));

                        try
                        {
                            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                            {
                                m.ToStream(stream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);
                                stream.Position = 0;
                                client.SendMessage(stream);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }

                        if (m != null)
                        {
                            m.Dispose();
                        }

                        client.Disconnect();
                    }
                }
                return(true);
            }
            else
            {
                using (SMTP_Client client = new SMTP_Client())
                {
                    client.Timeout = this.Timeout;
                    client.Connect(mSMTPServer, mSMTPPort);
                    client.EhloHelo(mSMTPServer);
                    AUTH_SASL_Client authhh = client.AuthGetStrongestMethod(musername, mSMTPPassword);
                    client.Auth(authhh);
                    client.MailFrom(mMailFrom, -1);
                    foreach (string address in toList.Keys)
                    {
                        client.RcptTo(address);
                    }



                    Mail_Message m = Create_PlainText_Html_Attachment_Image(toList, new Dictionary <string, string>()
                                                                            , mMailFrom,
                                                                            mMailFrom, MailSubject, mMailBody, attachments, "", "", false);

                    try
                    {
                        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                        {
                            m.ToStream(stream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);
                            stream.Position = 0;
                            client.SendMessage(stream);
                        }


                        return(true);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (m != null)
                        {
                            m.Dispose();
                        }
                        client.Disconnect();
                    }
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Completes relay session and does clean up. This method is thread-safe.
        /// </summary>
        /// <param name="exception">Exception happened or null if relay completed successfully.</param>
        public void Dispose(Exception exception)
        {
            try
            {
                lock (this)
                {
                    if (m_IsDisposed)
                    {
                        return;
                    }
                    try
                    {
                        m_pServer.OnSessionCompleted(this, exception);
                    }
                    catch {}
                    m_pServer.Sessions.Remove(this);
                    m_IsDisposed = true;

                    m_pLocalBindInfo = null;
                    m_pRelayItem = null;
                    m_pSmartHosts = null;
                    if (m_pSmtpClient != null)
                    {
                        m_pSmtpClient.Dispose();
                        m_pSmtpClient = null;
                    }
                    m_pTargets = null;
                    if (m_pActiveTarget != null)
                    {
                        m_pServer.RemoveIpUsage(m_pActiveTarget.Target.Address);
                        m_pActiveTarget = null;
                    }
                    m_pServer = null;
                }
            }
            catch (Exception x)
            {
                if (m_pServer != null)
                {
                    m_pServer.OnError(x);
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Start processing relay message.
        /// </summary>
        /// <param name="state">User data.</param>
        internal void Start(object state)
        {
            try
            {
                m_pSmtpClient = new SMTP_Client();
                m_pSmtpClient.LocalHostName = m_pLocalBindInfo.HostName;
                if (m_pServer.Logger != null)
                {
                    m_pSmtpClient.Logger = new Logger();
                    m_pSmtpClient.Logger.WriteLog += SmtpClient_WriteLog;
                }

                LogText("Starting to relay message '" + m_pRelayItem.MessageID + "' from '" +
                        m_pRelayItem.From + "' to '" + m_pRelayItem.To + "'.");

                // Get all possible target hosts for active recipient.
                List<string> targetHosts = new List<string>();
                if (m_RelayMode == Relay_Mode.Dns)
                {
                    foreach (string host in SMTP_Client.GetDomainHosts(m_pRelayItem.To))
                    {
                        try
                        {
                            foreach (IPAddress ip in Dns_Client.Resolve(host))
                            {
                                m_pTargets.Add(new Relay_Target(new IPEndPoint(ip, 25)));
                            }
                        }
                        catch
                        {
                            // Failed to resolve host name.

                            LogText("Failed to resolve host '" + host + "' name.");
                        }
                    }
                }
                else if (m_RelayMode == Relay_Mode.SmartHost)
                {
                    foreach (Relay_SmartHost smartHost in m_pSmartHosts)
                    {
                        try
                        {
                            m_pTargets.Add(
                                new Relay_Target(
                                    new IPEndPoint(Dns_Client.Resolve(smartHost.Host)[0], smartHost.Port),
                                    smartHost.SslMode,
                                    smartHost.UserName,
                                    smartHost.Password));
                        }
                        catch
                        {
                            // Failed to resolve smart host name.

                            LogText("Failed to resolve smart host '" + smartHost.Host + "' name.");
                        }
                    }
                }

                BeginConnect();
            }
            catch (Exception x)
            {
                Dispose(x);
            }
        }
        public void Send(ChannelMessage message)
        {
            var creds = CredentialsProvider.GetCredentials().ToNetworkCredential();

            Mail_Message msg = new Mail_Message();

            msg.MimeVersion = "1.0";
            msg.MessageID   = MIME_Utils.CreateMessageID();
            msg.Subject     = message.Context;
            msg.From        = message.From.ToMailBoxList();
            msg.ReplyTo     = message.ReturnTo == null?
                              message.From.ToAddressList() : message.ReturnTo.ToAddressList();

            if (String.IsNullOrEmpty(message.InReplyTo) == false)
            {
                msg.InReplyTo = message.InReplyTo;
            }

            msg.To = new Mail_t_AddressList();
            foreach (var address in message.To)
            {
                msg.To.Add(address.ToMailBox());
            }

            msg.Cc = new Mail_t_AddressList();
            foreach (var address in message.CC)
            {
                msg.Cc.Add(address.ToMailBox());
            }

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);

            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);

            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------------------------------------------------------------------
            MIME_Entity        entity_multipartAlternative      = new MIME_Entity();
            MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);

            contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);

            entity_multipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entity_multipartAlternative);

            //--- text/plain ----------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_plain = new MIME_Entity();
            MIME_b_Text text_plain        = new MIME_b_Text(MIME_MediaTypes.Text.plain);

            entity_text_plain.Body = text_plain;
            // Add text body if there is any
            if (message.BodyText != null && message.BodyText.Length > 0)
            {
                var bodyText = message.BodyText.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyText.EndsWith(Environment.NewLine))
                {
                    bodyText = bodyText + Environment.NewLine;
                }

                text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText);
            }

            multipartAlternative.BodyParts.Add(entity_text_plain);

            //--- text/html ------------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_html = new MIME_Entity();
            MIME_b_Text text_html        = new MIME_b_Text(MIME_MediaTypes.Text.html);

            entity_text_html.Body = text_html;
            if (message.BodyHtml != null && message.BodyHtml.Length > 0)
            {
                var bodyHtml = message.BodyHtml.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyHtml.EndsWith(Environment.NewLine))
                {
                    bodyHtml = bodyHtml + Environment.NewLine;
                }

                text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml);
            }

            multipartAlternative.BodyParts.Add(entity_text_html);

            foreach (var channelAttachment in message.Attachments)
            {
                MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream);
                MIME_Entity        attachment     = new MIME_Entity();
                attachment.Body = attachmentBody;

                // Has to happen before the following lines of code
                multipartMixed.BodyParts.Add(attachment);

                attachment.ContentType            = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename));
                attachment.ContentType.Param_Name = channelAttachment.Filename;

                MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment);
                contentDisposition.Param_FileName = channelAttachment.Filename;

                attachment.ContentDisposition      = contentDisposition;
                attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString();

                attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64);
            }

            // Inject headers
            if (!String.IsNullOrEmpty(message.MessageIdentifier))
            {
                msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier));
            }

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow))
            //    msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow));

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference))
            //    mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence))
            //    mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation))
            //    mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId))
            //    mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId);


            // Send message
            try
            {
                SMTP_Client client = new SMTP_Client();

                if ("/Settings/Channels/LoggerEnabled".AsKey(false))
                {
                    client.Logger = new LumiSoft.Net.Log.Logger();
                }

                // todo push this logic into the smtp client implementation itself
                if (Hostname == "smtp.live.com")
                {
                    // Hack for hotmail, first do a connect with no secured channel,
                    // then a STARTTLS
                    client.Connect(Hostname, Port, false);
                    client.StartTLS();
                }
                else
                {
                    client.Connect(Hostname, Port, IsSecured);
                }

                client.Authenticate(creds.UserName, creds.Password);

                using (MemoryStream ms = new MemoryStream())
                {
                    client.MailFrom(msg.From[0].Address, -1);

                    msg.ToStream(ms,
                                 new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    // Reset stream
                    ms.Seek(0, SeekOrigin.Begin);

                    foreach (var address in message.To)
                    {
                        client.RcptTo(address.Address);
                    }

                    foreach (var address in message.CC)
                    {
                        client.RcptTo(address.Address);
                    }

                    foreach (var address in message.BCC)
                    {
                        client.RcptTo(address.Address);
                    }

                    try
                    {
                        client.SendMessage(ms);
                    }
                    finally
                    {
                        client.Dispose();
                    }
                }
            }
            catch (SmtpFailedRecipientsException e)
            {
                throw new ChannelFunctionalException(e.Message, e)
                      {
                          DoNotRetry = true
                      };
            }
            catch (SmtpException e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
        }