// ------------------------ AddRecipient ----------------------------------
        public void AddRecipient(EmailAddress InAddress, MailAddressType InType)
        {
            try
            {
                switch (InType)
                {
                case MailAddressType.To:
                    mToRecipients.AddRecipient(InAddress);
                    break;

                case MailAddressType.Cc:
                    CCRecipients.AddRecipient(InAddress);
                    break;

                case MailAddressType.Bcc:
                    BCCRecipients.AddRecipient(InAddress);
                    break;
                }
            }
            catch (Exception e)
            {
                throw new MailException("Exception in AddRecipient: " + e.ToString( ));
            }
        }
Beispiel #2
0
        /// <summary>Returns the MailMessage as a RFC 822 formatted message</summary>
        public override string ToString()
        {
            StringBuilder         sb = new StringBuilder(60000);
            MimeHeaderLineBuilder lb = new MimeHeaderLineBuilder( );

            lb.Traits.SetEncoderCharSet(charset);

            // reply to email address
            sb.Append(
                MimeCommon.ConcatMessageLine(
                    lb.Traits,
                    "Reply-To:",
                    ReplyTo.ToMimeString(lb.Traits.EncoderCharSet),
                    MimeConstants.CrLf));

            // BgnTemp debug.  an already encoded from email address.
            if (mEncodedFromAddress != null)
            {
                sb.Append(mEncodedFromAddress + MimeConstants.CrLf);
            }
            else
            {
                // EndTemp debug.

                // send from email address
                sb.Append(
                    MimeCommon.ConcatMessageLine(
                        lb.Traits,
                        "From:",
                        From.ToMimeString(lb.Traits.EncoderCharSet),
                        MimeConstants.CrLf));
            }

            // send to email address
            sb.Append(
                MimeCommon.ConcatMessageLine(
                    lb.Traits,
                    "To:",
                    ToRecipients.ToMessageHeaderString(lb.Traits.EncoderCharSet),
                    MimeConstants.CrLf));

//			sb.Append( "Reply-To: " ) ;
//			sb.Append( ReplyTo.ToMimeString( charset )) ;
//			sb.Append( SmtpConstants.CrLf ) ;

//			sb.Append( "From: " + From.ToMimeStringToMessageHeaderString( charset )) ;
//			sb.Append( SmtpConstants.CrLf ) ;
//			sb.Append( "To: " + ToRecipients.ToMessageHeaderString( charset )) ;
//			sb.Append( SmtpConstants.CrLf ) ;

            if (CCRecipients.Count > 0)
            {
                sb.Append("CC: " + CCRecipients.ToMessageHeaderString(charset));
                sb.Append(SmtpConstants.CrLf);
            }

            if (BCCRecipients.Count > 0)
            {
                sb.Append("BCC: " + BCCRecipients.ToMessageHeaderString(charset));
                sb.Append(SmtpConstants.CrLf);
            }

            // message subject line.
            if (Stringer.IsNotEmpty(Subject))
            {
                lb.Clear( );
                lb.Append("Subject: ");
                lb.Append(Subject);
                sb.Append(lb.ToEncodedString( ) + MimeConstants.CrLf);
            }

            // BgnTemp debug.  an already encoded subject line.
            if (mEncodedSubject != null)
            {
                sb.Append(mEncodedSubject + MimeConstants.CrLf);
            }
            // EndTemp debug.

            // send timestamp
            lb
            .Clear( )
            .Append("Date: " + DateTime.Now.ToUniversalTime().ToString("R"));
            sb.Append(lb.ToEncodedString( ) + MimeConstants.CrLf);

            sb.Append(SmtpConfig.X_MAILER_HEADER + "\r\n");

            if (notification)
            {
                if (ReplyTo.FriendlyName != null && ReplyTo.FriendlyName.Length != 0)
                {
                    sb.Append("Disposition-Notification-To: " + MailEncoder.ConvertHeaderToQP(ReplyTo.FriendlyName, charset) + " <" + ReplyTo.Address + ">\r\n");
                }
                else
                {
                    sb.Append("Disposition-Notification-To: <" + ReplyTo.Address + ">\r\n");
                }
            }

            if (priority != null)
            {
                sb.Append("X-Priority: " + priority + "\r\n");
            }

            if (customHeaders != null)
            {
                for (IEnumerator i = customHeaders.GetEnumerator(); i.MoveNext();)
                {
                    MailHeader m = (MailHeader)i.Current;

                    if (m.name.Length >= 0 && m.body.Length >= 0)
                    {
                        sb.Append(m.name + ":" + MailEncoder.ConvertHeaderToQP(m.body, charset) + "\r\n");
                    }
                    else
                    {
                        // TODO: Check if below is within RFC spec.
                        sb.Append(m.name + ":\r\n");
                    }
                }
            }

            sb.Append("MIME-Version: 1.0\r\n");
            sb.Append(GetMessageBody());

            return(sb.ToString());
        }
Beispiel #3
0
        /// <summary>
        /// Send the message.
        /// </summary>
        /// <returns>
        /// True if it succeeds.
        /// </returns>
        public bool SendMail()
        {
            // Create a mail message.
            MimeMessage message = new MimeMessage();

            // Handle addresses.
            message.From.Add(new MailboxAddress(SenderName, SenderEmail));
            foreach (string address in Recipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.To.Add(new MailboxAddress(address.Trim()));
            }
            foreach (string address in CCRecipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.Cc.Add(new MailboxAddress(address.Trim()));
            }
            foreach (string address in BCCRecipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.Bcc.Add(new MailboxAddress(address.Trim()));
            }
            if (!String.IsNullOrEmpty(ReplyTo))
            {
                foreach (string address in ReplyTo.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.ReplyTo.Add(new MailboxAddress(address.Trim()));
                }
            }

            // Set up the subject, body, and attachments.
            message.Subject = Subject;
            var builder = new BodyBuilder();

            if (UseHtml)
            {
                builder.HtmlBody = Message;
            }
            else
            {
                builder.TextBody = Message;
            }
            foreach (string path in _attachments)
            {
                builder.Attachments.Add(path);
            }
            message.Body = builder.ToMessageBody();

            // Send the message.
            SmtpClient client;

            if (String.IsNullOrWhiteSpace(LogFile))
            {
                client = new SmtpClient();
            }
            else
            {
                client = new SmtpClient(new ProtocolLogger(LogFile));
            }
            using (client)
            {
                // Accept all SSL certificates (in case the server supports STARTTLS).
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Timeout = Timeout * 1000;
                // See https://unop.uk/sending-email-in-.net-core-with-office-365-and-mailkit/ for Office 365 or
                // https://unop.uk/advanced-email-sending-with-.net-core-and-mailkit/ for a more advanced guide
                SecureSocketOptions value = (SecureSocketOptions)SecurityOptions;
                client.Connect(MailServer, ServerPort, value);
                if (OAuthenticate != null)
                {
                    client.Authenticate(OAuthenticate);
                }
                else if (!String.IsNullOrWhiteSpace(UserName))
                {
                    // TODO: may have to use System.Text.Encoding.UTF8 as first parameter; see https://github.com/jstedfast/MailKit/issues/686
                    // See https://dotnetcoretutorials.com/2018/03/18/common-errors-sending-email-mailkit/ for common errors
                    client.Authenticate(UserName, Password);
                }
                client.Send(message);
                client.Disconnect(true);
            }
            client.Dispose();
            return(true);
        }