Example #1
1
		public void TestWriteTo (string text)
		{
			var builder = new BodyBuilder ();

			builder.Attachments.Add ("filename", new MemoryStream (Encoding.UTF8.GetBytes (text)));

			var body = builder.ToMessageBody ();

			using (var stream = new MemoryStream ()) {
				var options = FormatOptions.Default.Clone ();
				options.NewLineFormat = NewLineFormat.Dos;

				body.WriteTo (options, stream);
				stream.Position = 0;

				var multipart = (Multipart) MimeEntity.Load (stream);
				using (var input = ((MimePart) multipart[0]).ContentObject.Open ()) {
					var buffer = new byte[1024];
					int n;

					n = input.Read (buffer, 0, buffer.Length);

					var content = Encoding.UTF8.GetString (buffer, 0, n);

					Assert.AreEqual (text, content);
				}
			}
		}
Example #2
0
 /// <summary>
 /// MAIL KIT
 /// Info : http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/
 /// </summary>
 public static void SendEmail(string email, string name, string subject, string message,byte[] attachment = null,string attachmentName ="Facture")
 {
     var mimeMessage = new MimeMessage();
     mimeMessage.From.Add(new MailboxAddress(Configurations.Application.StolonsLabel, Configurations.Application.MailAddress));
     mimeMessage.To.Add(new MailboxAddress(name, email));
     mimeMessage.Subject = subject;
     var bodyBuilder = new BodyBuilder();
     if(attachment != null)
         bodyBuilder.Attachments.Add(attachmentName,attachment);
     bodyBuilder.HtmlBody = message;
     mimeMessage.Body = bodyBuilder.ToMessageBody();
     try
     {
         using (var client = new SmtpClient())
         {
             client.Connect(Configurations.Application.MailSmtp, Configurations.Application.MailPort, false);
             client.AuthenticationMechanisms.Remove("XOAUTH2");
             // Note: since we don't have an OAuth2 token, disable
             // the XOAUTH2 authentication mechanism.
             client.Authenticate(Configurations.Application.MailAddress, Configurations.Application.MailPassword);
             client.Send(mimeMessage);
             client.Disconnect(true);
         }
     }
     catch (Exception except)
     {
         Console.WriteLine("Error on sending mail : " + except.Message);
     }
 }
        public async Task MailKitSendAsync(string to, string subject, string message)
        {
            var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));
            mimeMessage.To.Add(new MailboxAddress(to, to));
            mimeMessage.Subject = subject;

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = message,
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(_smtpServer, _smtpPort, _enableSsl);
                client.Authenticate(_username, _password); // If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps

                await client.SendAsync(mimeMessage);

                client.Disconnect(true);
            }
        }
 /*
  * builds body parts of message
  */
 internal static MimeEntity BuildMessageBody(Node ip, Node dp)
 {
     BodyBuilder builder = new BodyBuilder();
     BuildBody(ip, dp, builder);
     BuildAttachments(ip, builder);
     return builder.ToMessageBody();
 }
Example #5
0
        public async void Send(string toAddress, string subject, string body, bool sendAsync = true)
        {
            var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));
            mimeMessage.To.Add(new MailboxAddress(toAddress));
            mimeMessage.Subject = subject;
            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = body
            };
            IEnumerable <InternetAddress> ccList = new List <InternetAddress>();

            foreach (var itemAppUser in _userDal.Users)
            {
                InternetAddress address = new MailboxAddress(itemAppUser.Email);
                mimeMessage.Cc.Add(address);
            }
            mimeMessage.Body = bodyBuilder.ToMessageBody();
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(_smtpServer, _smtpPort, _enableSsl);
                client.Authenticate(_username, _password); // If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps
                if (sendAsync)
                {
                    await client.SendAsync(mimeMessage);
                }
                else
                {
                    client.Send(mimeMessage);
                }
                client.Disconnect(true);
            }
        }
        public async void Send(string toAddress, string subject, string body, bool sendAsync = true)
        {
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));
            mimeMessage.To.Add(new MailboxAddress(toAddress));
            mimeMessage.Subject = subject;

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = body
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                client.Connect(_smtpServer, _smtpPort, _enableSsl);
                client.Authenticate(_username, _password);
                if (sendAsync)
                {
                    await client.SendAsync(mimeMessage);
                }
                else
                {
                    client.Send(mimeMessage);
                }
                client.Disconnect(true);
            }
        }
 /// <summary>
 /// Sets up the smtp server and the mail message
 /// </summary>
 public void init()
 {
     _smtp = new SmtpClient();
     _builder = new BodyBuilder();
     _message = null; // will be filled in with Hy's email
     _subject = "Busted - It's Up to You Invitation";
     _destinations = new List<String>();
 }
Example #8
0
        static void Main(string[] args)
        {
            var host        = "smtp.gmail.com";
            var port        = 465;
            var fromAdd     = "*****@*****.**";       //送信元アドレス
            var fromAddPass = "******";                           //送信元アドレスパスワード
            var toAdd       = "*****@*****.**";     //送信先アドレス
            var mailSubject = "エラー通知テスト";                           //メールタイトル
            var mailText    = "お疲れ様です。\r\nエラー通知のテストメールを送信いたしまします。"; //メール本文

            using (var smtp = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    //開発用のSMTPサーバが暗号化に対応していないときは、次の行をコメントアウト
                    //smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    smtp.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto);
                    //認証設定
                    smtp.Authenticate(fromAdd, fromAddPass);

                    //送信するメールを作成する
                    var mail    = new MimeKit.MimeMessage();
                    var builder = new MimeKit.BodyBuilder();
                    mail.From.Add(new MimeKit.MailboxAddress("", fromAdd));
                    mail.To.Add(new MimeKit.MailboxAddress("", toAdd));
                    //メールタイトル
                    mail.Subject = mailSubject;
                    //メール本文
                    MimeKit.TextPart textPart = new MimeKit.TextPart("Plain");
                    textPart.Text = mailText;

                    var multipart = new MimeKit.Multipart("mixed");
                    multipart.Add(textPart);
                    mail.Body = multipart;
                    //メールを送信する
                    smtp.Send(mail);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
                finally
                {
                    //SMTPサーバから切断する
                    smtp.Disconnect(true);
                }
            }
        }
Example #9
0
        private MimeMessage CreateMailMessage(string subject, string body)
        {
            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = body
            };

            var message = new MimeMessage
            {
                Sender  = MailboxAddress.Parse(this.From),
                Subject = subject,
                Body    = bodyBuilder.ToMessageBody()
            };

            return(message);
        }
        public static async Task<SendMessageResponse> SendMessageAsync(string accessToken,
            SendMessageRequest sendMessageRequest, string username)
        {
            var message = new MimeMessage();
            //message.From.Add(new MailboxAddress(sendMessageRequest.Message.));
            foreach (var to in sendMessageRequest.Message.ToRecipients)
            {
                message.To.Add(new MailboxAddress(to.EmailAddress.Name, to.EmailAddress.Address));
            }
            message.Subject = sendMessageRequest.Message.Subject;

            var builder = new BodyBuilder();

            // Set the plain-text version of the message text
            //builder.TextBody = @"";

            // Set the html version of the message text
            builder.HtmlBody = sendMessageRequest.Message.Body.Content;

            // Now we just need to set the message body and we're done
            message.Body = builder.ToMessageBody();
            var encodedEmail = Base64UrlEncode(message.ToString());
            var url = $"https://www.googleapis.com/upload/gmail/v1/users/{username}/messages/send?uploadType=media";
            var sendMessageResponse = new SendMessageResponse { Status = SendMessageStatusEnum.NotSent };
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    request.Content = new StringContent(encodedEmail, Encoding.UTF8, "message/rfc822");
                    using (var response = await client.SendAsync(request))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            sendMessageResponse.Status = SendMessageStatusEnum.Sent;
                            sendMessageResponse.StatusMessage = null;
                        }
                        else
                        {
                            sendMessageResponse.Status = SendMessageStatusEnum.Fail;
                            sendMessageResponse.StatusMessage = response.ReasonPhrase;
                        }
                    }
                }
            }
            return sendMessageResponse;
        }
Example #11
0
		public static void Complex ()
		{
			#region Complex
			var message = new MimeMessage ();
			message.From.Add (new MailboxAddress ("Joey", "*****@*****.**"));
			message.To.Add (new MailboxAddress ("Alice", "*****@*****.**"));
			message.Subject = "How you doin?";

			var builder = new BodyBuilder ();

			// Set the plain-text version of the message text
			builder.TextBody = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
";

			// In order to reference selfie.jpg from the html text, we'll need to add it
			// to builder.LinkedResources and then use its Content-Id value in the img src.
			var image = builder.LinkedResources.Add (@"C:\Users\Joey\Documents\Selfies\selfie.jpg");
			image.ContentId = MimeUtils.GenerateMessageId ();

			// Set the html version of the message text
			builder.HtmlBody = string.Format (@"<p>Hey Alice,<br>
<p>What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.<br>
<p>Will you be my +1?<br>
<p>-- Joey<br>
<center><img src=""cid:{0}""></center>", image.ContentId);

			// We may also want to attach a calendar event for Monica's party...
			builder.Attachments.Add (@"C:\Users\Joey\Documents\party.ics");

			// Now we just need to set the message body and we're done
			message.Body = builder.ToMessageBody ();
			#endregion
		}
Example #12
0
        static void Main(string[] args)
        {
            var client = new SmtpClient();

            client.Connect("smtp.gmail.com", 587, false);
            ICredentials credentials = new System.Net.NetworkCredential("username", "password");

            client.Authenticate(credentials);
            client.Authenticate("*****@*****.**", "Kikiriki123.");
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("*****@*****.**"));
            message.To.Add(new MailboxAddress("*****@*****.**"));
            var builder = new MimeKit.BodyBuilder();

            builder.HtmlBody = @"<html><head></head><body><p><b>bold</b>,
            i>italic</i> and <u>underlined</u></p></body></html>";
            message.Body     = builder.ToMessageBody();
            client.Send(message);
            Console.ReadLine();
        }
        public async Task <int> SendEmailConfirmationAsync(string email, string callbackUrl)
        {
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));
            mimeMessage.To.Add(new MailboxAddress(email));
            mimeMessage.Subject = "Confirm new account";

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = $"<p>If this email comes to your junk folder, copy and paste the link into your browser's address bar, OR click the 'Not Junk' link to move this email to your inbox. At which point, the link will become clickable and it will tell your email client that further emails from Systems Design is safe to put into the inbox.</p><br /><br /> {callbackUrl}"
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    client.Connect(_smtpServer, _smtpPort, _enableSsl);

                    client.Authenticate(_username, _password);

                    await client.SendAsync(mimeMessage);

                    _logger.LogInformation("A confirmation email was sent to {0}. Message sent: {1}", email, mimeMessage.Body);
                }
                catch (SmtpException ex)
                {
                    _logger.LogError("An error occurred sending a confimation email: {0}, Message:{1}", ex, ex.Message);
                    throw;
                }
                finally
                {
                    client.Disconnect(true);
                }
            }
            return(await Task.FromResult(0));
        }
        public async Task <int> SendEmailAsync(string email, string subject, string message)
        {
            // MIME : Multipurpose Internet Mail Extension
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));
            mimeMessage.To.Add(new MailboxAddress(email));
            mimeMessage.Subject = subject;

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = message
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    client.Connect(_smtpServer, _smtpPort, _enableSsl);
                    //If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps
                    client.Authenticate(_username, _password);
                    await client.SendAsync(mimeMessage);

                    _logger.LogInformation("A email was sent to {0}. Message sent: {1}", email, mimeMessage.Body);
                }
                catch (SmtpException ex)
                {
                    _logger.LogError("An error occurred sending a confimation email: {0}, Message:{1}", ex, ex.Message);
                    throw;
                }
                finally
                {
                    client.Disconnect(true);
                }
            }
            return(await Task.FromResult(0));
        }
Example #15
0
        public async Task Send(string toAddress, string subject, string body, bool sendAsync = true)

        {
            MimeMessage mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension

            mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));

            mimeMessage.To.Add(new MailboxAddress(string.Empty, toAddress));

            mimeMessage.Subject = subject;

            BodyBuilder bodyBuilder = new MimeKit.BodyBuilder

            {
                HtmlBody = body
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync(_smtpServer, _smtpPort, _enableSsl).ConfigureAwait(false);

                await client.AuthenticateAsync(_username.Trim(), _password.Trim()).ConfigureAwait(false);

                if (sendAsync)

                {
                    await client.SendAsync(mimeMessage).ConfigureAwait(false);
                }
                else

                {
                    client.Send(mimeMessage);
                }

                client.Disconnect(true);
            }
        }
Example #16
0
        public override void Execute()
        {
            if (!IsValidEmail(Invoice.Customer.Email))
                return;
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("Anchorage Kid to Kid", "*****@*****.**"));
            message.To.Add(new MailboxAddress(Invoice.Customer.ToString(), Invoice.Customer.Email));
            message.Subject = "Receipt: " + Invoice.Id;

            var body = new BodyBuilder();
            body.HtmlBody = GetHtmlBody(Invoice);
            body.TextBody = "";
            message.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                var userName = SharedDb.PosimDb.GetString("SELECT StringValue FROM  DBA.BYR_PREFS where PrefTitle = 'emailUN'");
                var pw = SharedDb.PosimDb.GetString("SELECT StringValue FROM  DBA.BYR_PREFS where PrefTitle = 'emailPW'");
                var credentials = new NetworkCredential(userName, pw);

                // Note: if the server requires SSL-on-connect, use the "smtps" protocol instead
                var uri = new Uri("smtp://smtp.gmail.com:587");

                using (var cancel = new CancellationTokenSource())
                {
                    client.Connect(uri, cancel.Token);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(credentials, cancel.Token);

                    client.Send(message, cancel.Token);
                    client.Disconnect(true, cancel.Token);
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to send mail!");
            Console.ReadKey();
            //Getting AWS credentials from App.config
            //note: see the app.config to get a example
            var credentials = new EnvironmentAWSCredentials();

            //Client SES instantiated
            var client = new AmazonSimpleEmailServiceClient(credentials, RegionEndpoint.USEast1);
            var mimeMessage = new MimeMessage();

            //Add sender e-mail address
            //Note: this e-mail address must to be allowed and checked by AWS SES
            mimeMessage.From.Add(new MailboxAddress("Test Sender", "*****@*****.**"));

            //Add  e-mail address destiny
            mimeMessage.To.Add(new MailboxAddress("Joel", "*****@*****.**"));
            mimeMessage.Subject = "Test";
            //Getting attachment stream
            var fileBytes = File.ReadAllBytes(@"C:\anyfile.pdf");

            var bodyBuilder = new BodyBuilder();
            bodyBuilder.TextBody = "Testing the body message";

            //You must to inform the mime-type of the attachment and his name
            bodyBuilder.Attachments.Add("AnyAttachment.pdf", fileBytes, new ContentType("application", "pdf"));
            mimeMessage.Body = bodyBuilder.ToMessageBody();

            //Map MimeMessage to MemoryStream, that is what SenRawEmailRequest accepts
            var rawMessage = new MemoryStream();
            mimeMessage.WriteTo(rawMessage);

            client.SendRawEmail(new SendRawEmailRequest(new RawMessage(rawMessage)));
            Console.WriteLine("Email Sended");

            Console.ReadKey();
        }
Example #18
0
        public static void SendVerificationEmail(string emailaddress, string validation_guid)
        {
            const string VERIFICATION_DOMAIN = "https://nzixo03fx1.execute-api.us-west-2.amazonaws.com/prod/emailvalidation?verificationstring="; //TODO: Move this to our domain name prior to launch
            const string FROM = "*****@*****.**"; //TODO: Change to real domain name
            const string SUBJECT = "Please verify your email address";
            string TO = emailaddress;
            string mBase64EncodedGuid = Convert.ToBase64String(Encoding.UTF8.GetBytes(emailaddress + ":" + validation_guid));

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("GEM CARRY EMAIL VERIFICATION", FROM));
            message.To.Add(new MailboxAddress("New Gamer", TO));
            message.Subject = SUBJECT;

            var builder = new BodyBuilder();
            builder.TextBody = string.Format("To activate your account, please click the following link to verifiy your email address {0}{1}", VERIFICATION_DOMAIN, mBase64EncodedGuid);
            builder.HtmlBody = string.Format("To activate your account, please click <a href={0}{1}> here</a> to verify your email address.",VERIFICATION_DOMAIN,mBase64EncodedGuid);

            message.Body = builder.ToMessageBody();

            var stream = new MemoryStream();
            message.WriteTo(stream);

            try
            {
                AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient();
                var request = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
                client.SendRawEmail(request);
            #if DEBUG
                logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Generating Validation Email for {0}.", emailaddress));
            #endif // DEBUG

            }
            catch (Exception ex)
            {
                logger.WriteLog(GameLogger.LogLevel.Error, ex.Message.ToString());
            }
        }
Example #19
0
        public bool SendEmail(string toAddress, string subject, string body, string fromName)
        {
            var mimeMessage = new MimeMessage();

            //numele app tau
            mimeMessage.From.Add(new MailboxAddress(fromName, _fromAddress));
            mimeMessage.To.Add(new MailboxAddress(toAddress));

            mimeMessage.Subject = subject;

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                HtmlBody = body
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(_smtpServer, _smtpPort, _enableSsl);

                client.Authenticate(_username, _password);
                try
                {
                    client.Send(mimeMessage);
                }
                catch (Exception ex)
                {
                    return(false);
                }

                client.Disconnect(true);

                return(true);
            }
        }
Example #20
0
        public async Task SendAsync(string from,string from_name, string to,string cc, string subject, string messageBody, string host)
        {
            

            System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;

            var message = new MimeMessage();
            var e_from = new MailboxAddress(from, from_name);
            e_from.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
            
            message.From.Add(e_from);

            var e_to = new MailboxAddress("", to);
            e_to.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");

            message.To.Add(e_to);

            if (cc != null && cc != "" )
            {
                message.Cc.Add(new MailboxAddress("", cc));
            }

            message.Subject = subject;
          

            var builder = new BodyBuilder();

            //Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment
            //var app_environment = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Runtime.RuntimePath;//
            var app_environment = host;

            var filename = "http://"+ app_environment + "/templates/Mail/Signature.html";

            WebClient clients = new WebClient();
            
            string mailboy = clients.DownloadString(new Uri(filename));


            //var mailboy = System.IO.File.ReadAllText(filename);
            var image_source = new Uri("http://" + app_environment + "/images/M32G2.png");

            
            var image = builder.LinkedResources.Add("M32G2.png", clients.DownloadData(image_source)) ;
            
            image.ContentId = Path.GetFileName("M32G2.png");


            //imagepath= app_environment.ApplicationBasePath + 

            mailboy = mailboy.Replace("#imageLogo#", image.ContentId);
            mailboy = mailboy.Replace("#body#", messageBody);
            
            
            builder.HtmlBody = mailboy;
            //message.Body.ContentLocation = "pt-PT";
            //builder.HtmlBody = messageBody;



            //builder.HtmlBody = string.Format(@"<p>Hey!</p><img src=""cid:{0}"">", image.ContentId);
           
            message.Body = builder.ToMessageBody();
            
            using (var client = new SmtpClient())
            {
               client.Connect("smtp.gmail.com", 587, false);

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "Meridian321");
                
                client.Send(message);
                client.Disconnect(true);
            }
            

        }
Example #21
0
        public async Task SendMultipleEmailAsync(
            SmtpOptions smtpOptions,
            string toCsv,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrEmpty(toCsv))
            {
                throw new ArgumentException("no to addresses provided");
            }

            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrEmpty(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            if (string.IsNullOrEmpty(plainTextMessage) && string.IsNullOrEmpty(htmlMessage))
            {
                throw new ArgumentException("no message provided");
            }

            


            var m = new MimeMessage();

            m.From.Add(new MailboxAddress("", from));

            string[] adrs = toCsv.Split(',');

            foreach (string item in adrs)
            {
                if (!string.IsNullOrEmpty(item)) { m.To.Add(new MailboxAddress("", item)); ; }
            }

            m.Subject = subject;
            m.Importance = MessageImportance.High;
           
            BodyBuilder bodyBuilder = new BodyBuilder();
            if (plainTextMessage.Length > 0)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (htmlMessage.Length > 0)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync(
                    smtpOptions.Server, 
                    smtpOptions.Port, 
                    smtpOptions.UseSsl).ConfigureAwait(false);
                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(
                        smtpOptions.User, 
                        smtpOptions.Password).ConfigureAwait(false);
                }

                await client.SendAsync(m).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }

        }
        private MimeMessage ExtractTnefMessage(TnefReader reader)
        {
            var tnefReader = reader.TnefPropertyReader;
            var builder = new BodyBuilder();
            var message = new MimeMessage();
            while (reader.ReadNextAttribute() && reader.AttributeLevel == TnefAttributeLevel.Message)
            {
                switch (reader.AttributeTag)
                {
                    case TnefAttributeTag.MapiProperties:
                        this.ExtractMapiProperties(reader, message, builder);
                        continue;
                    case TnefAttributeTag.DateReceived:
                        message.Date = tnefReader.ReadValueAsDateTime();
                        continue;
                    default:
                        continue;
                }
            }

            if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
            {
                ExtractAttachments(reader, builder);
            }

            message.Body = builder.ToMessageBody();

            return message;
        }
Example #23
0
        static MimeMessage ExtractTnefMessage(TnefReader reader)
        {
            var builder = new BodyBuilder ();
            var message = new MimeMessage ();

            while (reader.ReadNextAttribute ()) {
                if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
                    break;

                if (reader.AttributeLevel != TnefAttributeLevel.Message)
                    Assert.Fail ("Unknown attribute level.");

                var prop = reader.TnefPropertyReader;

                switch (reader.AttributeTag) {
                case TnefAttributeTag.RecipientTable:
                    ExtractRecipientTable (reader, message);
                    break;
                case TnefAttributeTag.MapiProperties:
                    ExtractMapiProperties (reader, message, builder);
                    break;
                case TnefAttributeTag.DateSent:
                    message.Date = prop.ReadValueAsDateTime ();
                    Console.WriteLine ("Message Attribute: {0} = {1}", reader.AttributeTag, message.Date);
                    break;
                case TnefAttributeTag.Body:
                    builder.TextBody = prop.ReadValueAsString ();
                    Console.WriteLine ("Message Attribute: {0} = {1}", reader.AttributeTag, builder.TextBody);
                    break;
                case TnefAttributeTag.TnefVersion:
                    Console.WriteLine ("Message Attribute: {0} = {1}", reader.AttributeTag, prop.ReadValueAsInt32 ());
                    break;
                case TnefAttributeTag.OemCodepage:
                    int codepage = prop.ReadValueAsInt32 ();
                    try {
                        var encoding = Encoding.GetEncoding (codepage);
                        Console.WriteLine ("Message Attribute: OemCodepage = {0}", encoding.HeaderName);
                    }
                    catch {
                        Console.WriteLine ("Message Attribute: OemCodepage = {0}", codepage);
                    }
                    break;
                default:
                    Console.WriteLine ("Message Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue ());
                    break;
                }
            }

            if (reader.AttributeLevel == TnefAttributeLevel.Attachment) {
                ExtractAttachments (reader, builder);
            } else {
                Console.WriteLine ("no attachments");
            }

            message.Body = builder.ToMessageBody ();

            return message;
        }
Example #24
0
        static void ExtractMapiProperties(TnefReader reader, MimeMessage message, BodyBuilder builder)
        {
            var prop = reader.TnefPropertyReader;

            while (prop.ReadNextProperty ()) {
                switch (prop.PropertyTag.Id) {
                case TnefPropertyId.InternetMessageId:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode) {
                        message.MessageId = prop.ReadValueAsString ();
                        Console.WriteLine ("Message Property: {0} = {1}", prop.PropertyTag.Id, message.MessageId);
                    } else {
                        Assert.Fail ("Unknown property type for Message-Id: {0}", prop.PropertyTag.ValueTnefType);
                    }
                    break;
                case TnefPropertyId.Subject:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode) {
                        message.Subject = prop.ReadValueAsString ();
                        Console.WriteLine ("Message Property: {0} = {1}", prop.PropertyTag.Id, message.Subject);
                    } else {
                        Assert.Fail ("Unknown property type for Subject: {0}", prop.PropertyTag.ValueTnefType);
                    }
                    break;
                case TnefPropertyId.RtfCompressed:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
                        var rtf = new TextPart ("rtf");
                        rtf.ContentType.Name = "body.rtf";

                        var converter = new RtfCompressedToRtf ();
                        var content = new MemoryStream ();

                        using (var filtered = new FilteredStream (content)) {
                            filtered.Add (converter);

                            using (var compressed = prop.GetRawValueReadStream ()) {
                                compressed.CopyTo (filtered, 4096);
                                filtered.Flush ();
                            }
                        }

                        rtf.ContentObject = new ContentObject (content);
                        content.Position = 0;

                        builder.Attachments.Add (rtf);

                        Console.WriteLine ("Message Property: {0} = <compressed rtf data>", prop.PropertyTag.Id);
                    } else {
                        Assert.Fail ("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;
                case TnefPropertyId.BodyHtml:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
                        var html = new TextPart ("html");
                        html.ContentType.Name = "body.html";
                        html.Text = prop.ReadValueAsString ();

                        builder.Attachments.Add (html);

                        Console.WriteLine ("Message Property: {0} = {1}", prop.PropertyTag.Id, html.Text);
                    } else {
                        Assert.Fail ("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;
                case TnefPropertyId.Body:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
                        var plain = new TextPart ("plain");
                        plain.ContentType.Name = "body.txt";
                        plain.Text = prop.ReadValueAsString ();

                        builder.Attachments.Add (plain);

                        Console.WriteLine ("Message Property: {0} = {1}", prop.PropertyTag.Id, plain.Text);
                    } else {
                        Assert.Fail ("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;
                default:
                    Console.WriteLine ("Message Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue ());
                    break;
                }
            }
        }
Example #25
0
        static void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var filter = new BestEncodingFilter ();
            var prop = reader.TnefPropertyReader;
            MimePart attachment = null;
            int outIndex, outLength;
            byte[] attachData;
            string text;

            Console.WriteLine ("Extracting attachments...");

            do {
                if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
                    Assert.Fail ("Expected attachment attribute level: {0}", reader.AttributeLevel);

                switch (reader.AttributeTag) {
                case TnefAttributeTag.AttachRenderData:
                    attachment = new MimePart ();
                    builder.Attachments.Add (attachment);
                    break;
                case TnefAttributeTag.Attachment:
                    if (attachment == null)
                        break;

                    while (prop.ReadNextProperty ()) {
                        switch (prop.PropertyTag.Id) {
                        case TnefPropertyId.AttachLongFilename:
                            attachment.FileName = prop.ReadValueAsString ();

                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
                            break;
                        case TnefPropertyId.AttachFilename:
                            if (attachment.FileName == null) {
                                attachment.FileName = prop.ReadValueAsString ();
                                Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
                            } else {
                                Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
                            }
                            break;
                        case TnefPropertyId.AttachContentLocation:
                            text = prop.ReadValueAsString ();
                            if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
                                attachment.ContentLocation = new Uri (text, UriKind.Absolute);
                            else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
                                attachment.ContentLocation = new Uri (text, UriKind.Relative);
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;
                        case TnefPropertyId.AttachContentBase:
                            text = prop.ReadValueAsString ();
                            attachment.ContentBase = new Uri (text, UriKind.Absolute);
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;
                        case TnefPropertyId.AttachContentId:
                            attachment.ContentId = prop.ReadValueAsString ();
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentId);
                            break;
                        case TnefPropertyId.AttachDisposition:
                            text = prop.ReadValueAsString ();
                            if (attachment.ContentDisposition == null)
                                attachment.ContentDisposition = new ContentDisposition (text);
                            else
                                attachment.ContentDisposition.Disposition = text;
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;
                        case TnefPropertyId.AttachData:
                            if (prop.IsEmbeddedMessage) {
                                Console.WriteLine ("Attachment Property: {0} is an EmbeddedMessage", prop.PropertyTag.Id);
                                var stream = prop.GetRawValueReadStream ();
                                using (var tnef = new TnefReader (stream, reader.MessageCodepage, reader.ComplianceMode)) {
                                    var embedded = ExtractTnefMessage (tnef);
                                    Console.WriteLine ("embedded attachments = {0}", embedded.BodyParts.Count ());
                                    foreach (var part in embedded.BodyParts)
                                        builder.Attachments.Add (part);
                                }
                            } else {
                                Console.WriteLine ("Attachment Property: {0} is not an EmbeddedMessage", prop.PropertyTag.Id);
                            }
                            break;
                        default:
                            Console.WriteLine ("Attachment Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue ());
                            break;
                        }
                    }
                    break;
                case TnefAttributeTag.AttachData:
                    if (attachment == null)
                        break;

                    attachData = prop.ReadValueAsBytes ();
                    filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
                    attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
                    attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
                    filter.Reset ();
                    break;
                default:
                    Console.WriteLine ("Attachment Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue ());
                    break;
                }
            } while (reader.ReadNextAttribute ());
        }
Example #26
0
        public async Task<bool> SendMail(MimeMessage message, string emailDestination, bool moveToDest)
        {
            if (_setupInProgress) return false;
            _emailIsSending = true;
            _timer.Stop();

            try
            {
                var client = _smtpClient;

                var buildMessage = new MimeMessage();
                buildMessage.Sender = new MailboxAddress(_factory.MailBoxName, _factory.GetConfiguration().UserName);
                buildMessage.From.Add(new MailboxAddress(_factory.MailBoxName, _factory.GetConfiguration().UserName));
                buildMessage.To.Add(new MailboxAddress(emailDestination, emailDestination));

                buildMessage.ReplyTo.AddRange(message.From.Mailboxes);
                buildMessage.ReplyTo.AddRange(message.Cc.Mailboxes);
                buildMessage.From.AddRange(message.From.Mailboxes);
                buildMessage.From.AddRange(message.Cc.Mailboxes);
                buildMessage.Subject = message.Subject;

                var builder = new BodyBuilder();

                foreach (
                    var bodyPart in
                        message.BodyParts.Where(bodyPart => !bodyPart.ContentType.MediaType.Equals("text")))
                {
                    builder.LinkedResources.Add(bodyPart);
                }

                string addresses = message.From.Mailboxes.Aggregate("",
                    (current, address) => current + (address.Address + "; "));

                string ccAddresses = message.Cc.Mailboxes.Aggregate("", (a, b) => a + (b.Address + "; "));

                string toAddresses = message.To.Mailboxes.Aggregate("", (a, b) => a + (b.Address + "; "));

                if (message.TextBody != null)
                {
                    builder.TextBody = "***Message From " + _factory.GetConfiguration().MailBoxName + "*** \n" +
                                       "Message_pulled_by: " + emailDestination +
                                       "\nSent from: " + addresses +
                                       "\nSent to: " + toAddresses +
                                       "\nCC'd on email: " + ccAddresses + "\nMessage Date: " +
                                       message.Date.ToLocalTime().ToString("F")
                                       + "\n---\n" + message.TextBody;
                }

                if (message.HtmlBody != null)
                {
                    builder.HtmlBody = "***Message From " + _factory.GetConfiguration().MailBoxName + "*** <br/>" +
                                       "Message_pulled_by: " + emailDestination +
                                       "<br/>Sent from: " + addresses + "<br/>Sent to: " + toAddresses +
                                       "<br/>CC'd on email: " + ccAddresses + "<br/>Message Date:" +
                                       message.Date.ToLocalTime().ToString("F") +
                                       "<br/>---<br/>" + message.HtmlBody;
                }

                buildMessage.Body = builder.ToMessageBody();

                await client.SendAsync(buildMessage);

                return true;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                await Setup();
                return false;
            }
            finally
            {
                _emailIsSending = false;
                _timer.Start();
            }
        }
        private void ExtractMapiProperties(TnefReader reader, MimeMessage message, BodyBuilder builder)
        {
            var tnefPropertyReader = reader.TnefPropertyReader;
            while (tnefPropertyReader.ReadNextProperty())
            {
                switch (tnefPropertyReader.PropertyTag.Id)
                {
                    case TnefPropertyId.RtfCompressed:
                        var memoryStream = new MemoryStream();
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                        {
                            var textPart = new TextPart("rtf");
                            textPart.ContentType.Name = "body.rtf";
                            RtfCompressedToRtf rtfCompressedToRtf = new RtfCompressedToRtf();
                            //var memoryStream = new MemoryStream();
                            using (var filteredStream = new FilteredStream(memoryStream))
                            {
                                filteredStream.Add(rtfCompressedToRtf);
                                using (Stream rawValueReadStream = tnefPropertyReader.GetRawValueReadStream())
                                {
                                    rawValueReadStream.CopyTo(filteredStream, 4096);
                                    filteredStream.Flush();
                                }
                            }

                            textPart.ContentObject = new ContentObject(memoryStream, ContentEncoding.Default);
                            memoryStream.Position = 0L;
                            builder.Attachments.Add(textPart);
                            continue;
                        }

                        memoryStream.Dispose();
                        continue;
                    case TnefPropertyId.BodyHtml:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                        {
                            var textPart = new TextPart("html");
                            textPart.ContentType.Name = "body.html";
                            textPart.Text = tnefPropertyReader.ReadValueAsString();
                            builder.Attachments.Add(textPart);
                            continue;
                        }

                        continue;
                    case TnefPropertyId.InternetMessageId:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                        {
                            message.MessageId = tnefPropertyReader.ReadValueAsString();
                            continue;
                        }

                        continue;
                    case TnefPropertyId.Subject:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                        {
                            message.Subject = tnefPropertyReader.ReadValueAsString();
                            continue;
                        }

                        continue;
                    case TnefPropertyId.Body:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                        {
                            var textPart = new TextPart("plain");
                            textPart.ContentType.Name = "body.txt";
                            textPart.Text = tnefPropertyReader.ReadValueAsString();
                            builder.Attachments.Add(textPart);
                            continue;
                        }

                        continue;
                    case TnefPropertyId.ConversationTopic:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                        {
                            message.Subject = tnefPropertyReader.ReadValueAsString();
                            continue;
                        }

                        continue;
                    case TnefPropertyId.SenderName:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                        {
                            var sender = new MailboxAddress(string.Empty, tnefPropertyReader.ReadValueAsString());
                            message.Sender = sender;
                        }

                        continue;
                    case (TnefPropertyId)Mapi.ID.PR_PRIMARY_SEND_ACCOUNT:
                        if (tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.String8 || tnefPropertyReader.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                        {
                            var senderEmail = new MailboxAddress(string.Empty, tnefPropertyReader.ReadValueAsString());
                            message.Sender = senderEmail;
                        }

                        continue;
                    default:
                        try
                        {
                            tnefPropertyReader.ReadValue();
                            continue;
                        }
                        catch
                        {
                            continue;
                        }
                }
            }
        }
        /*
         * builds attachments of message, if any
         */
        private static void BuildAttachments(Node ip, BodyBuilder builder)
        {
            if (!ip.Contains("attachments") && !ip.Contains("linked-attachments"))
                return;

            Node getRoot = new Node();
            ActiveEvents.Instance.RaiseActiveEvent(
                typeof(SmtpHelper),
                "magix.file.get-base-path",
                getRoot);
            string rootDirectory = getRoot["path"].Get<string>();

            if (ip.Contains("attachments"))
            {
                foreach (Node idx in ip["attachments"])
                {
                    builder.Attachments.Add(rootDirectory + idx.Get<string>());
                }
            }
            if (ip.Contains("linked-attachments"))
            {
                foreach (Node idx in ip["linked-attachments"])
                {
                    builder.LinkedResources.Add(rootDirectory + idx.Get<string>());
                }
            }
        }
Example #29
0
        private MimeKit.MimeMessage ISFEmail(JGA_PGS_ENT consignatario, List<JGA_PGS_CXE> contactosConsig, JGA_PGS_AGEN agenciaExterior,
                                 List<JGA_PGS_CXE> contactosAgenE, JGA_PGS_ENT embarcador, List<JGA_PGS_CXE> contactosEmb,
                                 JGA_PGS_USR usuario, JGA_REPORTESPDF jga_reportespdf, Byte[] binary)
        {
            var message = new MimeMessage();
            //Emisor del correo.
            message.From.Add(new MailboxAddress(usuario.USR_NAME, usuario.USR_EMAIL));
            //Receptores del correo.
            message.To.Add(new MailboxAddress(consignatario.ENT_NOMBRE, consignatario.ENT_MAIL1));
            if (contactosConsig.Count > 0)
            {
                foreach (var item in contactosConsig)
                {
                    message.To.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email1));
                    if (item.CXE_email2 != null)
                    {
                        message.To.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email2));
                    }
                }
            }
            message.To.Add(new MailboxAddress(agenciaExterior.AGEN_NOMBRE, agenciaExterior.AGEN_MAIL));
            if (contactosAgenE.Count > 0)
            {
                foreach (var item in contactosAgenE)
                {
                    message.To.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email1));
                    if (item.CXE_email2 != null)
                    {
                        message.To.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email2));
                    }
                }
            }
            message.Cc.Add(new MailboxAddress(embarcador.ENT_NOMBRE, embarcador.ENT_MAIL1));
            if (contactosEmb.Count > 0)
            {
                foreach (var item in contactosEmb)
                {
                    message.Cc.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email1));
                    if (item.CXE_email2 != null)
                    {
                        message.Cc.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email2));
                    }
                }
            }
            //Asunto del correo.
            message.Subject = "10+2 " + jga_reportespdf.CONSECUTIVO;

            var builder = new BodyBuilder();
            //Correo en texto plano
            builder.TextBody = @"Buenas\n
                                Adjunto encontrá(n) el 10+2 " + jga_reportespdf.CONSECUTIVO +
                                "\nFavor confirmar recibido \nGracias";
            //correo en HTML
            builder.HtmlBody = @"<p>Buenas<br>" +
                                "Adjunto encontrá(n) el 10+2 " + jga_reportespdf.CONSECUTIVO + "<br>" +
                                "Favor confirmar recibido<br>" +
                                "Gracias</p>";
            //acá adjuntamos el archivo PDF
            builder.Attachments.Add("ISF" + jga_reportespdf.CONSECUTIVO + ".pdf", binary);
            message.Body = builder.ToMessageBody();
            return message;
        }
		public void TestReferenceByContentId ()
		{
			var builder = new BodyBuilder ();

			builder.HtmlBody = "<html>This is an <b>html</b> body.</html>";

			builder.LinkedResources.Add ("empty.gif", new byte[0], new ContentType ("image", "gif"));
			builder.LinkedResources.Add ("empty.jpg", new byte[0], new ContentType ("image", "jpg"));

			foreach (var attachment in builder.LinkedResources)
				attachment.ContentId = MimeUtils.GenerateMessageId ();

			var body = builder.ToMessageBody ();

			Assert.IsInstanceOf<MultipartRelated> (body, "Expected a multipart/related.");

			var related = (MultipartRelated) body;

			Assert.AreEqual ("text/html", related.ContentType.Parameters["type"], "The type parameter does not match.");

			var root = related.Root;

			Assert.IsNotNull (root, "The root document should not be null.");
			Assert.IsTrue (root.ContentType.IsMimeType ("text", "html"), "The root document has an unexpected mime-type.");

			// Note: MimeKit no longer sets the "start" parameter if the root is the first MIME part due to a bug in Thunderbird.
			Assert.IsNull (related.ContentType.Parameters["start"], "The start parameter should be null.");

			for (int i = 0; i < related.Count; i++) {
				var cid = new Uri (string.Format ("cid:{0}", related[i].ContentId));
				string mimeType, charset;

				Assert.IsTrue (related.Contains (cid), "Contains failed.");
				Assert.AreEqual (i, related.IndexOf (cid), "IndexOf did not return the expected index.");

				using (var stream = related.Open (cid, out mimeType, out charset)) {
					Assert.AreEqual (related[i].ContentType.MimeType, mimeType, "mime-types did not match.");
				}

				Assert.DoesNotThrow (() => related.Open (cid).Dispose ());
			}
		}
Example #31
0
 private MimeKit.MimeMessage notifEmail(JGA_PROYECCION proyeccion, JGA_PGS_ENT suplidor, List<JGA_PGS_CXE> contactosSup, JGA_PGS_ENT embarcador, List<JGA_PGS_CXE> contactosEmb, JGA_PGS_USR usuario)
 {
     JGA_PGS_PTOS puertoDest = db.JGA_PGS_PTOS.SingleOrDefault(x => x.PTOS_CODPTO == proyeccion.PROY_PTOIN);
     var message = new MimeMessage();
     message.From.Add(new MailboxAddress(usuario.USR_NAME, usuario.USR_EMAIL));
     message.To.Add(new MailboxAddress(suplidor.ENT_NOMBRE, suplidor.ENT_MAIL1));
     if (suplidor.ENT_MAIL2 != null)
     {
         message.To.Add(new MailboxAddress(suplidor.ENT_NOMBRE, suplidor.ENT_MAIL2));
     }
     if (contactosSup.Count > 0)
     {
         foreach (var item in contactosSup)
         {
             message.To.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email1));
             if (item.CXE_email2 != null)
             {
                 message.To.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email2));
             }
         }
     }
     message.Cc.Add(new MailboxAddress(embarcador.ENT_NOMBRE, embarcador.ENT_MAIL1));
     if (embarcador.ENT_MAIL2 != null)
     {
         message.Cc.Add(new MailboxAddress(embarcador.ENT_NOMBRE, embarcador.ENT_MAIL2));
     }
     if (contactosEmb.Count > 0)
     {
         foreach (var item in contactosEmb)
         {
             message.Cc.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email1));
             if (item.CXE_email2 != null)
             {
                 message.Cc.Add(new MailboxAddress(item.CXE_nombre, item.CXE_email2));
             }
         }
     }
     //Asunto del correo
     message.Subject = "Llegada de contenedor a planta " + suplidor.ENT_NOMBRE + " / " + proyeccion.JGA_BKG_SOL.JGA_PGS_NAV.NAV_NOMBRE + " - " + proyeccion.JGA_BKG_SOL.JGA_PGS_NAV.JGA_PGS_DEST.SingleOrDefault(x => x.DEST_IDDEST == proyeccion.JGA_BKG_SOL.SOL_DEST).DEST_DESCRIP + " " + proyeccion.JGA_BKG_SOL.SOL_SEMANA;
     //acá creamos una variable para la contrucción del email.
     var builder = new BodyBuilder();
     //Correo en texto plano
     builder.TextBody = @"";
     //correo en HTML
     builder.HtmlBody = @"<div>
                             <p>Buenos días.<br />Estos son los datos del contenedor que estará llegando el día " + proyeccion.PROY_FECCOLOCACION + " a planta.</p>"+
                             "<h3>"+proyeccion.PROY_CONSEC+"</h3>"+
                             "<table border='3' style='border-color:black; width:80%; text-align:center;'>"+
                                 "<thead>"+
                                     "<tr style='background-color:blue; color: white;'>"+
                                         "<td class='header'>Contenedor</td>"+
                                         "<td class='header'>Marchamo</td>"+
                                         "<td class='header'>Barco</td>"+
                                         "<td class='header'>Puerto destino</td>"+
                                         "<td class='header'>Naviera</td>"+
                                     "</tr>"+
                                 "</thead>"+
                                 "<tbody>"+
                                     "<tr>"+
                                         "<td>" + proyeccion.PROY_CONTENEDOR+"</td>"+
                                         "<td>"+proyeccion.PROY_MARCHAMO+"</td>"
                                         +"<td>"+proyeccion.PROY_BARCO+"</td>"+
                                         "<td>"+puertoDest.PTOS_NOMBRE+"</td>"+
                                         "<td>"+proyeccion.JGA_BKG_SOL.JGA_PGS_NAV.NAV_NOMBRE+"</td>"+
                                      "</tr>"+
                                   "</tbody>"+
                               "</table><br />"+
                               "<p>Por favor confirmar recibido.<br />Saludos.</p>"+
                         "</div>";
     message.Body = builder.ToMessageBody();
     return message;
 }
Example #32
0
		static void ExtractAttachments (TnefReader reader, BodyBuilder builder)
		{
			var attachMethod = TnefAttachMethod.ByValue;
			var filter = new BestEncodingFilter ();
			var prop = reader.TnefPropertyReader;
			MimePart attachment = null;
			int outIndex, outLength;
			TnefAttachFlags flags;
			string[] mimeType;
			byte[] attachData;
			DateTime time;
			string text;

			Console.WriteLine ("Extracting attachments...");

			do {
				if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
					Assert.Fail ("Expected attachment attribute level: {0}", reader.AttributeLevel);

				switch (reader.AttributeTag) {
				case TnefAttributeTag.AttachRenderData:
					Console.WriteLine ("Attachment Attribute: {0}", reader.AttributeTag);
					attachMethod = TnefAttachMethod.ByValue;
					attachment = new MimePart ();
					break;
				case TnefAttributeTag.Attachment:
					Console.WriteLine ("Attachment Attribute: {0}", reader.AttributeTag);
					if (attachment == null)
						break;

					while (prop.ReadNextProperty ()) {
						switch (prop.PropertyTag.Id) {
						case TnefPropertyId.AttachLongFilename:
							attachment.FileName = prop.ReadValueAsString ();

							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
							break;
						case TnefPropertyId.AttachFilename:
							if (attachment.FileName == null) {
								attachment.FileName = prop.ReadValueAsString ();
								Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
							} else {
								Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
							}
							break;
						case TnefPropertyId.AttachContentLocation:
							text = prop.ReadValueAsString ();
							if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
								attachment.ContentLocation = new Uri (text, UriKind.Absolute);
							else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
								attachment.ContentLocation = new Uri (text, UriKind.Relative);
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachContentBase:
							text = prop.ReadValueAsString ();
							attachment.ContentBase = new Uri (text, UriKind.Absolute);
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachContentId:
							attachment.ContentId = prop.ReadValueAsString ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentId);
							break;
						case TnefPropertyId.AttachDisposition:
							text = prop.ReadValueAsString ();
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition (text);
							else
								attachment.ContentDisposition.Disposition = text;
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachMethod:
							attachMethod = (TnefAttachMethod) prop.ReadValueAsInt32 ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachMethod);
							break;
						case TnefPropertyId.AttachMimeTag:
							text = prop.ReadValueAsString ();
							mimeType = text.Split ('/');
							if (mimeType.Length == 2) {
								attachment.ContentType.MediaType = mimeType[0].Trim ();
								attachment.ContentType.MediaSubtype = mimeType[1].Trim ();
							}
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachFlags:
							flags = (TnefAttachFlags) prop.ReadValueAsInt32 ();
							if ((flags & TnefAttachFlags.RenderedInBody) != 0) {
								if (attachment.ContentDisposition == null)
									attachment.ContentDisposition = new ContentDisposition (ContentDisposition.Inline);
								else
									attachment.ContentDisposition.Disposition = ContentDisposition.Inline;
							}
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, flags);
							break;
						case TnefPropertyId.AttachData:
							var stream = prop.GetRawValueReadStream ();
							var content = new MemoryStream ();
							var guid = new byte[16];

							if (attachMethod == TnefAttachMethod.EmbeddedMessage) {
								var tnef = new TnefPart ();

								foreach (var param in attachment.ContentType.Parameters)
									tnef.ContentType.Parameters[param.Name] = param.Value;

								if (attachment.ContentDisposition != null)
									tnef.ContentDisposition = attachment.ContentDisposition;

								attachment = tnef;
							}

							stream.Read (guid, 0, 16);

							stream.CopyTo (content, 4096);

							var buffer = content.GetBuffer ();
							filter.Flush (buffer, 0, (int) content.Length, out outIndex, out outLength);
							attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
							attachment.ContentObject = new ContentObject (content);
							filter.Reset ();

							Console.WriteLine ("Attachment Property: {0} has GUID {1}", prop.PropertyTag.Id, new Guid (guid));

							builder.Attachments.Add (attachment);
							break;
						case TnefPropertyId.DisplayName:
							attachment.ContentType.Name = prop.ReadValueAsString ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentType.Name);
							break;
						case TnefPropertyId.AttachSize:
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition ();

							attachment.ContentDisposition.Size = prop.ReadValueAsInt64 ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentDisposition.Size.Value);
							break;
						default:
							Console.WriteLine ("Attachment Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue ());
							break;
						}
					}
					break;
				case TnefAttributeTag.AttachData:
					Console.WriteLine ("Attachment Attribute: {0}", reader.AttributeTag);
					if (attachment == null || attachMethod != TnefAttachMethod.ByValue)
						break;

					attachData = prop.ReadValueAsBytes ();
					filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
					attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
					attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
					filter.Reset ();

					builder.Attachments.Add (attachment);
					break;
				case TnefAttributeTag.AttachCreateDate:
					time = prop.ReadValueAsDateTime ();

					if (attachment != null) {
						if (attachment.ContentDisposition == null)
							attachment.ContentDisposition = new ContentDisposition ();

						attachment.ContentDisposition.CreationDate = time;
					}

					Console.WriteLine ("Attachment Attribute: {0} = {1}", reader.AttributeTag, time);
					break;
				case TnefAttributeTag.AttachModifyDate:
					time = prop.ReadValueAsDateTime ();

					if (attachment != null) {
						if (attachment.ContentDisposition == null)
							attachment.ContentDisposition = new ContentDisposition ();

						attachment.ContentDisposition.ModificationDate = time;
					}

					Console.WriteLine ("Attachment Attribute: {0} = {1}", reader.AttributeTag, time);
					break;
				case TnefAttributeTag.AttachTitle:
					text = prop.ReadValueAsString ();

					if (attachment != null && string.IsNullOrEmpty (attachment.FileName))
						attachment.FileName = text;

					Console.WriteLine ("Attachment Attribute: {0} = {1}", reader.AttributeTag, text);
					break;
				default:
					Console.WriteLine ("Attachment Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue ());
					break;
				}
			} while (reader.ReadNextAttribute ());
		}
 /*
  * builds body of message
  */
 private static void BuildBody(Node ip, Node dp, BodyBuilder builder)
 {
     if (ip.Contains("body"))
     {
         if (ip["body"].Contains("html"))
         {
             string body = Expressions.GetExpressionValue<string>(ip["body"]["html"].Get<string>(), dp, ip, false);
             builder.HtmlBody = body;
         }
         if (ip["body"].Contains("plain"))
         {
             string body = Expressions.GetExpressionValue<string>(ip["body"]["plain"].Get<string>(), dp, ip, false);
             builder.TextBody = body;
         }
     }
 }
        private void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var tnefAttachMethod = TnefAttachMethod.ByValue;
            var bestEncodingFilter = new BestEncodingFilter();
            var tnefPropertyReader = reader.TnefPropertyReader;
            MimePart mimePart = null;
            do
            {
                int outputIndex;
                int outputLength;
                switch (reader.AttributeTag)
                {
                    case TnefAttributeTag.AttachData:
                        if (mimePart != null && tnefAttachMethod == TnefAttachMethod.ByValue)
                        {
                            byte[] numArray = tnefPropertyReader.ReadValueAsBytes();
                            bestEncodingFilter.Flush(numArray, 0, numArray.Length, out outputIndex, out outputLength);
                            mimePart.ContentTransferEncoding = bestEncodingFilter.GetBestEncoding(EncodingConstraint.SevenBit, 78);
                            mimePart.ContentObject = new ContentObject(new MemoryStream(numArray, false), ContentEncoding.Default);
                            bestEncodingFilter.Reset();
                            builder.Attachments.Add(mimePart);
                            break;
                        }
                        break;
                    case TnefAttributeTag.AttachRenderData:
                        tnefAttachMethod = TnefAttachMethod.ByValue;
                        mimePart = new MimePart();
                        break;
                    case TnefAttributeTag.Attachment:
                        if (mimePart != null)
                        {
                            while (tnefPropertyReader.ReadNextProperty())
                            {
                                switch (tnefPropertyReader.PropertyTag.Id)
                                {
                                    case TnefPropertyId.AttachData:
                                        using (var rawValueReadStream = tnefPropertyReader.GetRawValueReadStream())
                                        {
                                            using (var memoryStream = new MemoryStream())
                                            {

                                                byte[] buffer = new byte[16];
                                                if (tnefAttachMethod == TnefAttachMethod.EmbeddedMessage)
                                                {
                                                    TnefPart tnefPart = new TnefPart();
                                                    foreach (Parameter parameter in mimePart.ContentType.Parameters)
                                                    {
                                                        tnefPart.ContentType.Parameters[parameter.Name] = parameter.Value;
                                                    }

                                                    if (mimePart.ContentDisposition != null)
                                                    {
                                                        tnefPart.ContentDisposition = mimePart.ContentDisposition;
                                                    }

                                                    mimePart = tnefPart;
                                                }
                                                rawValueReadStream.Read(buffer, 0, 16);
                                                rawValueReadStream.CopyTo(memoryStream, 4096);
                                                byte[] input = memoryStream.ToArray();
                                                bestEncodingFilter.Flush(input, 0, (int)memoryStream.Length, out outputIndex, out outputLength);
                                                mimePart.ContentTransferEncoding = bestEncodingFilter.GetBestEncoding(EncodingConstraint.SevenBit, 78);
                                                mimePart.ContentObject = new ContentObject(memoryStream, ContentEncoding.Default);
                                                bestEncodingFilter.Reset();
                                                builder.Attachments.Add(mimePart);
                                            }
                                        }

                                        continue;
                                    case TnefPropertyId.AttachFilename:
                                        if (String.IsNullOrEmpty(mimePart.FileName))
                                        {
                                            mimePart.FileName = tnefPropertyReader.ReadValueAsString();
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachMethod:
                                        tnefAttachMethod = (TnefAttachMethod)tnefPropertyReader.ReadValueAsInt32();
                                        continue;
                                    case TnefPropertyId.AttachLongFilename:
                                        mimePart.FileName = tnefPropertyReader.ReadValueAsString();
                                        continue;
                                    case TnefPropertyId.AttachMimeTag:
                                        string[] strArray = tnefPropertyReader.ReadValueAsString().Split('/');
                                        if (strArray.Length == 2)
                                        {
                                            mimePart.ContentType.MediaType = strArray[0].Trim();
                                            mimePart.ContentType.MediaSubtype = strArray[1].Trim();
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachContentBase:
                                        var uriString = tnefPropertyReader.ReadValueAsString();
                                        mimePart.ContentBase = new Uri(uriString, UriKind.Absolute);
                                        continue;
                                    case TnefPropertyId.AttachContentId:
                                        mimePart.ContentId = tnefPropertyReader.ReadValueAsString();
                                        continue;
                                    case TnefPropertyId.AttachContentLocation:
                                        var uriString2 = tnefPropertyReader.ReadValueAsString();
                                        if (Uri.IsWellFormedUriString(uriString2, UriKind.Absolute))
                                        {
                                            mimePart.ContentLocation = new Uri(uriString2, UriKind.Absolute);
                                            continue;
                                        }

                                        if (Uri.IsWellFormedUriString(uriString2, UriKind.Relative))
                                        {
                                            mimePart.ContentLocation = new Uri(uriString2, UriKind.Relative);
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachFlags:
                                        if ((tnefPropertyReader.ReadValueAsInt32() & 4) != 0)
                                        {
                                            if (mimePart.ContentDisposition == null)
                                            {
                                                mimePart.ContentDisposition = new ContentDisposition("inline");
                                                continue;
                                            }

                                            mimePart.ContentDisposition.Disposition = "inline";
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachDisposition:
                                        var disposition = tnefPropertyReader.ReadValueAsString();
                                        if (mimePart.ContentDisposition == null)
                                        {
                                            mimePart.ContentDisposition = new ContentDisposition(disposition);
                                            continue;
                                        }

                                        mimePart.ContentDisposition.Disposition = disposition;
                                        continue;
                                    case TnefPropertyId.AttachSize:
                                        if (mimePart.ContentDisposition == null)
                                        {
                                            mimePart.ContentDisposition = new ContentDisposition();
                                        }

                                        mimePart.ContentDisposition.Size = new long?(tnefPropertyReader.ReadValueAsInt64());
                                        continue;
                                    case TnefPropertyId.DisplayName:
                                        mimePart.ContentType.Name = tnefPropertyReader.ReadValueAsString();
                                        continue;
                                    default:
                                        continue;
                                }
                            }
                            break;
                        }
                        break;
                    case TnefAttributeTag.AttachTitle:
                        var name = tnefPropertyReader.ReadValueAsString();
                        if (mimePart != null && String.IsNullOrEmpty(mimePart.FileName))
                        {
                            mimePart.FileName = name;
                            break;
                        }

                        break;
                    case TnefAttributeTag.AttachCreateDate:
                        var creationDateTime = tnefPropertyReader.ReadValueAsDateTime();
                        if (mimePart != null)
                        {
                            if (mimePart.ContentDisposition == null)
                            {
                                mimePart.ContentDisposition = new ContentDisposition();
                            }

                            mimePart.ContentDisposition.CreationDate = new DateTimeOffset(creationDateTime);
                            break;
                        }

                        break;
                    case TnefAttributeTag.AttachModifyDate:
                        var modifyDateTime = tnefPropertyReader.ReadValueAsDateTime();
                        if (mimePart != null)
                        {
                            if (mimePart.ContentDisposition == null)
                            {
                                mimePart.ContentDisposition = new ContentDisposition();
                            }

                            mimePart.ContentDisposition.ModificationDate = new DateTimeOffset(modifyDateTime);
                            break;
                        }

                        break;
                }
            }

            while (reader.ReadNextAttribute());
        }
Example #35
0
		static void TestUnicode (DkimSignatureAlgorithm signatureAlgorithm, DkimCanonicalizationAlgorithm bodyAlgorithm, string expectedHash)
		{
			var headers = new [] { HeaderId.From, HeaderId.To, HeaderId.Subject, HeaderId.Date };
			var signer = CreateSigner (signatureAlgorithm);
			var message = new MimeMessage ();

			message.From.Add (new MailboxAddress ("", "*****@*****.**"));
			message.To.Add (new MailboxAddress ("", "*****@*****.**"));
			message.Subject = "This is a unicode message";
			message.Date = DateTimeOffset.Now;

			var builder = new BodyBuilder ();
			builder.TextBody = " تست  ";
			builder.HtmlBody = "  <div> تست </div> ";
			message.Body = builder.ToMessageBody ();

			((Multipart) message.Body).Boundary = "=-MultipartAlternativeBoundary";
			((Multipart) message.Body)[1].ContentId = null;

			message.Body.Prepare (EncodingConstraint.EightBit);

			message.Sign (signer, headers, DkimCanonicalizationAlgorithm.Simple, bodyAlgorithm);

			var dkim = message.Headers[0];

			Console.WriteLine ("{0}", dkim.Value);

			VerifyDkimBodyHash (message, signatureAlgorithm, expectedHash);

			Assert.IsTrue (message.Verify (dkim, new DummyPublicKeyLocator (DkimKeys.Public)), "Failed to verify DKIM-Signature.");
		}
Example #36
0
		private MimeMessage BuildMimeMessage(
			string from,
			string fromAlias,
			string toCsv,
			string toAlias,
			string subject,
			string body,
			bool htmlBody,
			string replyTo)
		{
			MimeMessage emailMessage = new MimeMessage();
			emailMessage.From.Add(new MailboxAddress(fromAlias ?? string.Empty, from));

			string[] addresses = toCsv.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

			foreach (string address in addresses)
			{
				emailMessage.To.Add(new MailboxAddress(toAlias ?? string.Empty, address));
			}

			if (!string.IsNullOrEmpty(replyTo))
			{
				emailMessage.ReplyTo.Add(new MailboxAddress(string.Empty, replyTo));
			}

			emailMessage.Subject = subject;

			if (addresses.Length != 0)
			{
				// Send multiple emails.
				emailMessage.Importance = MessageImportance.High;
			}

			BodyBuilder bodyBuilder = new BodyBuilder();

			if (htmlBody)
			{
				bodyBuilder.HtmlBody = body;
			}
			else
			{
				bodyBuilder.TextBody = body;
			}

			emailMessage.Body = bodyBuilder.ToMessageBody();

			return emailMessage;
		}
Example #37
0
        public void Test(SmtpSettingsModel settings)
        {
            if (!SetupInfo.IsVisibleSettings(ManagementType.SmtpSettings.ToString()))
            {
                throw new BillingException(Resource.ErrorNotAllowedOption, "Smtp");
            }

            var config = ToSmtpSettingsConfig(settings ?? CurrentSmtpSettings);

            if (config.EnableAuth && config.CredentialsUserPassword.Equals(FakePassword))
            {
                var model = ToSmtpSettingsModel(config);
                model.CredentialsUserPassword = FullSmtpSettings.CredentialsUserPassword;
                config = ToSmtpSettingsConfig(model);
            }

            var sslCertificatePermit = ConfigurationManager.AppSettings["mail.certificate-permit"] != null &&
                                       Convert.ToBoolean(ConfigurationManager.AppSettings["mail.certificate-permit"]);

            var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var toAddress   = new MailboxAddress(currentUser.UserName, currentUser.Email);
            var fromAddress = new MailboxAddress(config.SenderDisplayName, config.SenderAddress);

            var mimeMessage = new MimeMessage
            {
                Subject = Core.Notify.WebstudioNotifyPatternResource.subject_smtp_test
            };

            mimeMessage.From.Add(fromAddress);

            mimeMessage.To.Add(toAddress);

            var bodyBuilder = new MimeKit.BodyBuilder
            {
                TextBody = Core.Notify.WebstudioNotifyPatternResource.pattern_smtp_test
            };

            mimeMessage.Body = bodyBuilder.ToMessageBody();

            mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

            using (var client = new MailKit.Net.Smtp.SmtpClient
            {
                ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                                                      sslCertificatePermit ||
                                                      MailKit.MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors),
                Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds
            })
            {
                client.Connect(config.Host, config.Port,
                               config.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None);

                if (config.EnableAuth)
                {
                    client.Authenticate(config.CredentialsUserName,
                                        config.CredentialsUserPassword);
                }

                client.Send(FormatOptions.Default, mimeMessage, CancellationToken.None);
            }
        }
Example #38
0
        public async Task SendEmailAsync(
            SmtpOptions smtpOptions,
            string to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if(string.IsNullOrEmpty(plainTextMessage) && string.IsNullOrEmpty(htmlMessage))
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();
           
            m.From.Add(new MailboxAddress("", from));
            m.To.Add(new MailboxAddress("", to));
            m.Subject = subject;
            //m.Importance = MessageImportance.Normal;
            //Header h = new Header(HeaderId.Precedence, "Bulk");
            //m.Headers.Add()

            BodyBuilder bodyBuilder = new BodyBuilder();
            if(plainTextMessage.Length > 0)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (htmlMessage.Length > 0)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();
            
            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, smtpOptions.UseSsl);
                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if(smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password);
                }
                
                client.Send(m);
                client.Disconnect(true);
            }

        }
Example #39
-1
		public void TestReferenceByContentId ()
		{
			var builder = new BodyBuilder ();

			builder.HtmlBody = "<html>This is an <b>html</b> body.</html>";

			builder.LinkedResources.Add ("empty.gif", new byte[0], new ContentType ("image", "gif"));
			builder.LinkedResources.Add ("empty.jpg", new byte[0], new ContentType ("image", "jpg"));

			foreach (var attachment in builder.LinkedResources)
				attachment.ContentId = MimeUtils.GenerateMessageId ();

			var body = builder.ToMessageBody ();

			Assert.IsInstanceOfType (typeof (MultipartRelated), body, "Expected a multipart/related.");

			var related = (MultipartRelated) body;

			Assert.AreEqual ("text/html", related.ContentType.Parameters["type"], "The type parameter does not match.");

			var root = related.Root;

			Assert.IsNotNull (root, "The root document should not be null.");
			Assert.IsTrue (root.ContentType.Matches ("text", "html"), "The root document has an unexpected mime-type.");

			var start = "<" + root.ContentId + ">";

			Assert.AreEqual (start, related.ContentType.Parameters["start"], "The start parameter does not match.");

			for (int i = 0; i < related.Count; i++) {
				var cid = new Uri (string.Format ("cid:{0}", related[i].ContentId));

				Assert.AreEqual (i, related.IndexOf (cid), "IndexOf did not return the expected index.");
			}
		}
Example #40
-1
		public void TestReferenceByContentLocation ()
		{
			var builder = new BodyBuilder ();

			builder.HtmlBody = "<html>This is an <b>html</b> body.</html>";

			builder.LinkedResources.Add ("empty.gif", new byte[0], new ContentType ("image", "gif"));
			builder.LinkedResources.Add ("empty.jpg", new byte[0], new ContentType ("image", "jpg"));

			var body = builder.ToMessageBody ();

			Assert.IsInstanceOf<MultipartRelated> (body, "Expected a multipart/related.");

			var related = (MultipartRelated) body;

			Assert.AreEqual ("text/html", related.ContentType.Parameters["type"], "The type parameter does not match.");

			var root = related.Root;

			Assert.IsNotNull (root, "The root document should not be null.");
			Assert.IsTrue (root.ContentType.Matches ("text", "html"), "The root document has an unexpected mime-type.");

			// Note: MimeKit no longer sets the "start" parameter if the root is the first MIME part due to a bug in Thunderbird.
			//var start = "<" + root.ContentId + ">";

			//Assert.AreEqual (start, related.ContentType.Parameters["start"], "The start parameter does not match.");

			for (int i = 1; i < related.Count; i++)
				Assert.AreEqual (i, related.IndexOf (related[i].ContentLocation), "IndexOf did not return the expected index.");
		}
Example #41
-1
		public static void Simple ()
		{
			#region Simple
			var message = new MimeMessage ();
			message.From.Add (new MailboxAddress ("Joey", "*****@*****.**"));
			message.To.Add (new MailboxAddress ("Alice", "*****@*****.**"));
			message.Subject = "How you doin?";

			var builder = new BodyBuilder ();

			// Set the plain-text version of the message text
			builder.TextBody = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
";

			// We may also want to attach a calendar event for Monica's party...
			builder.Attachments.Add (@"C:\Users\Joey\Documents\party.ics");

			// Now we just need to set the message body and we're done
			message.Body = builder.ToMessageBody ();
			#endregion
		}