コード例 #1
0
        /// <summary>
        /// Sends email
        /// </summary>
        /// <param name="Subject">Mail Subject</param>
        /// <param name="Body">Message Body</param>
        public void SendEmail(string Subject, string Body)
        {
            try
            {
                using (SmtpClient smtp = new SmtpClient(_host,_port))
                {
                    // Create message
                    MailMessage message = new MailMessage(_smtpUserName,
                        _destinationAddress, Subject, Body);

                    // Authenticate to server
                    smtp.Authenticate = true;
                    smtp.Username = _smtpUserName;
                    smtp.Password = _smtpPassword;

                    // Send message
                    smtp.Send(message);
                }
            }
            catch (SmtpException e)
            {
                // Exception handling here
                Console.DEBUG_ACTIVITY(e.Message);
                Console.DEBUG_ACTIVITY("Error Code: " + e.ErrorCode.ToString());

                if (AlarmByZones.AlarmByZones.SdCardEventLogger.IsSDCardAvailable() && AlarmByZones.Alarm.ConfigDefault.Data.STORE_EXCEPTION)
                {
                    AlarmByZones.AlarmByZones.SdCardEventLogger.saveFile(DateTime.Now.ToString("d_MMM_yyyy--HH_mm_ss") + ".log",
                        "Exception trying to send an email.\nErrorCode: " + e.ErrorCode.ToString()+
                        "\nException Message: " + e.Message, "Exception");
                }
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: PavelBansky/microframework
        public static void Main()
        {
            MailMessage message = new MailMessage();
            // Set sender name and address
            message.From = new MailAddress("*****@*****.**", "Foo Bar");

            // Set recipient address
            message.To.Add(new MailAddress("*****@*****.**", "John Doe"));
            message.Cc.Add(new MailAddress("*****@*****.**", "The Boss"));

            message.Subject = "Hello World";
            message.Body = "Good news,<br />from now on you can send e-mails from <b>.NET Micro Framework</b>.";
            // Format body as HTML
            message.IsBodyHtml = true;

            // Create new attachment and define it's name
            Attachment attachment = new Attachment("Snowflake.gif");
            attachment.ContentType = "image/gif";
            attachment.TransferEncoding = TransferEncoding.Base64;
            // Attachment content
            attachment.Content = Base64.Encode(Resources.GetBytes(
                                               Resources.BinaryResources.Snowflake_gif),
                                               true);

            // Add attachment to message
            message.Attachments.Add(attachment);

            // Create new SMTP instance
            SmtpClient smtp = new SmtpClient("smtp.contoso.com", 25);
            try
            {
                // Authenicate to server
                smtp.Authenticate = true;
                smtp.Username = "******";
                smtp.Password = "******";

                // Send message
                smtp.Send(message);
            }
            catch (SmtpException e)
            {
                // Exception handling here
                Debug.Print(e.Message);
                Debug.Print("Error Code: " + e.ErrorCode.ToString());
            }
            finally
            {
                smtp.Dispose();
            }
        }
コード例 #3
0
        /// <summary>
        /// Creates message body from MailMessage.
        /// </summary>
        /// <param name="message">MailMessage to be processed.</param>
        /// <returns>String suitable for SMTP transaction.</returns>
        private string ProcessMessage(MailMessage message)
        {
            string result = "Subject: " + message.Subject + "\r\n";
            result += "From: ";
            if (message.From.DisplayName != null)
                result += message.From.DisplayName + " <" + message.From.Address + ">";
            else
                result += message.From.Address;

            result += "\r\n";

            result += ProcessRcpt("To", message.To);
            result += ProcessRcpt("Cc", message.Cc);
            result += ProcessRcpt("Bcc", message.Bcc);

            DateTime now = DateTime.Now;
            result += "Date: " + now.ToString("ddd, d MMM yyyy HH:mm:ss \r\n");

            result += message.Headers;
            if (message.Headers.Length > 0 && !StrEndWith(message.Headers, "\r\n"))
                result += "\r\n";

            // We need special header when attachments are present
            if (message.Attachments.Count > 0)
            {
                result += "MIME-Version: 1.0\r\n";
                result += "Content-Type: multipart/mixed; boundary=\"frontier\"\r\n";
                result += "\r\n--frontier\r\n";
                result += ProcessBody(message);

                // Add all attachements
                foreach (Attachment attachment in message.Attachments)
                {
                    result += "\r\n--frontier\r\n";
                    result += "Content-type: " + attachment.ContentType;
                    result += ";\r\n\tname=\"" + attachment.Name + "\"\r\n";

                    result += "Content-Transfer-Encoding: ";
                    switch (attachment.TransferEncoding)
                    {
                        case TransferEncoding.QuotedPrintable:
                            result += "quoted-printable";
                            break;
                        case TransferEncoding.Base64:
                            result += "base64";
                            break;
                        case TransferEncoding.SevenBit:
                            result += "7bit";
                            break;
                        default:
                            result += "unknown";
                            break;
                    }
                    result += "\r\n";

                    if (attachment.ContentId != null)
                        result += "Content-ID: <" + attachment.ContentId + ">\r\n";

                    result += "Content-Disposition: ";
                    result += (attachment.Inline) ? "inline" : "attachment";
                    result += ";\r\n\tfilename=\"" + attachment.Name + "\"\r\n\r\n";

                    result += attachment.Content;
                }

                result += "\r\n--frontier--\r\n";
            }
            else
                result += ProcessBody(message);

            // Double all dots after line-breaks
            int i = 0;
            while ((i = result.IndexOf("\r\n.", i)) > -1)
            {
                result = result.Substring(0, i) + "." + result.Substring(i);
                i += 3;
            }

            return result;
        }
コード例 #4
0
        /// <summary>
        /// Creates message body wrapped in the appropriate content type header.
        /// </summary>
        /// <param name="message">MailMessage to process.</param>
        /// <returns>Message body.</returns>
        private string ProcessBody(MailMessage message)
        {
            string result = string.Empty;
            if (message.IsBodyHtml)
                result += "Content-Type: text/html";
            else
                result += "Content-Type: text/plain";

            return result + ";\r\n\tcharset=\"UTF-8\"\r\n\r\n" + message.Body;
        }
コード例 #5
0
 /// <summary>
 /// Sends the specified message to an SMTP server for delivery.
 /// </summary>
 /// <param name="from">Address information of the message sender.</param>
 /// <param name="to">Address that message is sent to.</param>
 /// <param name="subject">Subject line of the message.</param>
 /// <param name="body">Contains the message body.</param>
 /// <exception cref="ArgumentNullException">from or to is null reference</exception>
 /// <exception cref="ArgumentException">from or to is String.Empty ("")</exception>        
 /// <exception cref="SmtpException">connection or session errors</exception>
 /// <example>
 /// This code send simple e-mail message.
 /// No authentication to server is used.
 /// <code>
 /// using (SmtpClient smtp = new SmtpClient("smtp.hostname.net", 25))
 ///	{
 ///		// Send message
 ///		smtp.Send("*****@*****.**",
 ///				  "*****@*****.**",
 ///				  "Good news",
 ///				  "How are you Foo?");
 ///	}
 /// </code>
 /// </example>
 public void Send(string from, string to, string subject, string body)
 {
     MailMessage msg = new MailMessage(from, to, subject, body);
     Send(msg);
 }
コード例 #6
0
        /// <summary>
        /// Sends the specified message to an SMTP server for delivery.
        /// </summary>
        /// <param name="message">Bansky.SPOT.Mail.MailMessage that contains message to send.</param>
        /// <exception cref="ArgumentNullException">Message or From is null reference.</exception>
        /// <exception cref="ArgumentOutOfRangeException">There are no recipients in To, CC, and Bcc.</exception>
        /// <exception cref="SmtpException">The connection or session failed.</exception>
        /// <example>
        /// This code sends e-mail message and use authentication to server
        /// <code>
        ///	using (SmtpClient smtp = new SmtpClient("smtp.hostname.net", 25))
        ///	{
        ///		// Create message
        ///		MailMessage message = new MailMessage("*****@*****.**",
        ///											  "*****@*****.**",
        ///											  "Good news",
        ///											  "How are you Foo?");
        ///
        ///		// Authenicate to server
        ///		smtp.Authenticate = true;
        ///		smtp.Username = "******";
        ///		smtp.Password = "******";
        ///
        ///		// Send message
        ///		smtp.Send(message);
        ///	}
        /// </code>
        /// This code sends HTML formated e-mail message with attachment to more recipients.
        /// <code>
        ///	MailMessage message = new MailMessage();
        ///	// Set sender name and address
        ///	message.From = new MailAddress("*****@*****.**", "Foo Bar");
        ///	
        ///	// Set recipients
        ///	message.To.Add(new MailAddress("*****@*****.**", "John Doe"));
        ///	message.Cc.Add(new MailAddress("*****@*****.**"));
        ///	
        ///	message.Subject = "Hello World";
        ///	message.Body = "Good news,<br />from now on you can send e-mails from <b>.NET Micro Framework</b>.";
        ///	// Format body as HTML
        ///	message.IsBodyHtml = true;
        ///	
        ///	// Create new attachment and define it's name
        ///	Attachment attachment = new Attachment("Snwoflake.gif");        
        ///	attachment.ContentType = "image/gif";
        ///	attachment.TransferEncoding = TransferEncoding.Base64;
        ///	// Attachment content
        ///	attachment.Content = Base64.Encode( Resources.GetBytes(
        ///	                                    Resources.BinaryResources.Snowflake_gif),
        ///	                                    true);
        ///	
        ///	// Add attachment to message
        ///	message.Attachments.Add(attachment);
        ///	
        ///	// Create new SMTP instance
        ///	SmtpClient smtp = new SmtpClient("smtp.contoso.com", 25);
        ///	try
        ///	{
        ///		// Authenicate to server
        ///		smtp.Authenticate = true;
        ///		smtp.Username = "******";
        ///		smtp.Password = "******";
        ///	
        ///		// Send message
        ///		smtp.Send(message);
        ///	}
        ///	catch (SmtpException e)
        ///	{
        ///		// Exception handling here 
        ///		Debug.Print(e.Message);
        ///		Debug.Print("Error Code: " + e.ErrorCode.ToString());
        ///	}
        ///	finally
        ///	{
        ///		smtp.Dispose();
        ///	}
        /// </code>
        /// </example>
        public void Send(MailMessage message)
        {
            if (message == null)
                throw new ArgumentNullException();

            if (message.To.Count == 0
                && message.Cc.Count == 0
                && message.Bcc.Count == 0)
                    throw new ArgumentOutOfRangeException();

            try
            {
                // Get server's IP address.
                IPHostEntry hostEntry = Dns.GetHostEntry(this.Host);
                // Create socket and connect to the server's IP address and port
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(new IPEndPoint(hostEntry.AddressList[0], this.Port));
            }
            catch (Exception e)
            {
                throw new SmtpException(SmtpErrorCode.ConnectionFailed, e);
            }

            GetResponse("220", SmtpErrorCode.BadResponse);

            if (Authenticate)
                DoAuthentication(Username, Password);
            else
                SendCommand("HELO " + Domain, "250", SmtpErrorCode.BadResponse);

            SendCommand("MAIL From:<" + message.From.Address +">", "250", SmtpErrorCode.FromFailed);

            if (message.To.Count > 0)
                DoRcpt("To", message.To);

            if (message.Cc.Count > 0)
                DoRcpt("To", message.Cc);

            if (message.Bcc.Count > 0)
                DoRcpt("To", message.Bcc);

            SendCommand("DATA", "354", SmtpErrorCode.DataFailed);
            SendCommand(ProcessMessage(message) + "\r\n.\r\n", "250", SmtpErrorCode.DataFailed);

            SendCommand("QUIT", "221", SmtpErrorCode.DataFailed);

            socket.Close();
        }