A MIME message.

A message consists of header fields and, optionally, a body.

The body of the message can either be plain text or it can be a tree of MIME entities such as a text/plain MIME part and a collection of file attachments.

예제 #1
10
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress(_settings.Value.Author, _settings.Value.Email));
            emailMessage.To.Add(new MailboxAddress("", email));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart("html") {Text = message};
            try
            {
                var client = new SmtpClient();
                //     {
                // client.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                // client.Authenticate(_settings.Value.Email, _settings.Value.Password);
                //  client.Send(emailMessage);
                // client.Disconnect(true);
                await client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                await client.AuthenticateAsync(_settings.Value.Email, _settings.Value.Password);

                await client.SendAsync(emailMessage);
                await client.DisconnectAsync(true);
                //  }
            }
            catch (Exception ex) //todo add another try to send email
            {
                var e = ex;
                throw;
            }
           
        }
예제 #2
4
        public static void Generic(string[] args)
        {
            MainActivity = new MainActivity ();

            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("test", "*****@*****.**"));
            message.To.Add (new MailboxAddress (MainActivity.nome, MainActivity.email));
            message.Subject = "Obrigado por se candidatar";

            message.Body = new TextPart ("plain") {
                Text = @"Obrigado por se candidatar, assim que tivermos uma vaga disponível

            para programador entraremos em contato."

            };

            using (var client = new SmtpClient ()) {
                client.Connect ("smtp.test.com", 587, false);

                // 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 ("test", "password");

                client.Send (message);
                client.Disconnect (true);
            }
        }
예제 #3
3
        public void Send(EmailDependencies email)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.To.Add(new MailboxAddress(email.ToName, email.ToAddress));
                message.To.Add(new MailboxAddress(email.FromName, email.FromAddress));

                message.Subject = email.Title;
                message.Body = new TextPart("html") { Text = email.content };

                using (var client = new SmtpClient())
                {
                    client.Connect("mail.bizmonger.net", 587, false);

                    // 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(Configuration.ServerEmail, Configuration.Password);

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ex.GetBaseException().Message;
                Debug.WriteLine(errorMessage);
            }
        }
예제 #4
2
 public void SendMessage() {
     string msg = "";
     switch (CurrEmailType) {
         case EmailType.PRENOTA:
             msg = PrenotaSubject;
             FromMailAddress = PrenotaFromAddress;
             break;
         case EmailType.INFO:
             msg = InfoSubject;
             FromMailAddress = InfoFromAddress;
             break;
     }
     string subject = string.Format(msg, Message.Nome, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
     string body = string.Format("Nome : {0}\nNumero : {1}\nE-Mail : {2}\nMessaggio :\n{3}", Message.Nome, Message.Telefono, Message.Email, Message.Messaggio);
     var message = new MimeMessage();
     message.From.Add(FromMailAddress);
     message.To.Add(ToAddress);
     message.Subject = subject;
     message.Body = new TextPart("plain") {Text = body};
     try {
         using (var client = new SmtpClient()) {
             client.Connect("smtp.gmail.com", 465, true);
             client.AuthenticationMechanisms.Remove("XOAUTH");
             client.Authenticate("*****@*****.**", "At066bn1!");
             client.Send(message);
             client.Disconnect(true);
         }
         Result = EmailResult.SUCCESS;
         MessageResult = "Messaggio inviato correttamente";
     } catch (Exception ex) {
         Result = EmailResult.FAIL;
         MessageResult = ex.Message;
     }
 }
예제 #5
0
 public MessageViewModel(MimeMessage message)
 {
     _msg = message;
     var pvm = new PartViewModel(message.Body);
     pvm.IsExpanded = true;
     _main = new[] {pvm};
 }
예제 #6
0
파일: Form1.cs 프로젝트: kitokun/mailerApp
        static async void SendMailAsync(string FromAddress, string Password, string Contain, string Title, string ToAddress)
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MimeKit.MailboxAddress(FromAddress, FromAddress));
            message.To.Add(new MimeKit.MailboxAddress(ToAddress, ToAddress));
            message.Subject = Title;
            var textPart = new MimeKit.TextPart(MimeKit.Text.TextFormat.Plain);

            textPart.Text = @Contain;
            message.Body  = textPart;
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    await client.ConnectAsync("smtp.gmail.com", 587);

                    await client.AuthenticateAsync(FromAddress, Password);

                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
                catch (Exception ex)
                {
                    Form2 form2 = new Form2();
                    form2.text(ex.ToString());

                    form2.ShowDialog();
                }
            }
        }
예제 #7
0
        private static void SendConfirmationEmail(GmailService gmail, Dictionary <string, string> dict)
        {
            MailMessage mailmsg = new MailMessage();

            {
                mailmsg.Subject = dict["subject"];
                mailmsg.Body    = string.Format(dict["HTML"], dict["link"]);
                mailmsg.From    = new MailAddress(dict["from"]);
                mailmsg.To.Add(new MailAddress(dict["to"]));
                mailmsg.IsBodyHtml = true;
            }
            ////add attachment if specified
            if (dict.ContainsKey("attachement"))
            {
                if (File.Exists(dict["attachment"]))
                {
                    Attachment data = new Attachment(dict["attachment"]);
                    mailmsg.Attachments.Add(data);
                }
                else
                {
                    Console.WriteLine("Error: Invalid Attachemnt");
                }
            }
            //Make mail message a Mime message
            MimeKit.MimeMessage mimemessage = MimeKit.MimeMessage.CreateFromMailMessage(mailmsg);
            Google.Apis.Gmail.v1.Data.Message finalmessage = new Google.Apis.Gmail.v1.Data.Message();
            finalmessage.Raw = Base64UrlEncode(mimemessage.ToString());
            var result = gmail.Users.Messages.Send(finalmessage, "me").Execute();
        }
예제 #8
0
		public async Task Should_return_multiple_emails_when_sent()
		{
		    using (var sut = GetSut())
		    {
		        var msg = new MimeMessage();
		        msg.From.Add(new MailboxAddress("", "*****@*****.**"));
		        msg.To.Add(new MailboxAddress("", "*****@*****.**"));
		        msg.Subject = "subject";
		        msg.Body = new TextPart("plain") {Text = "body"};

		        var msg2 = new MimeMessage();
		        msg2.From.Add(new MailboxAddress("", "*****@*****.**"));
		        msg2.To.Add(new MailboxAddress("", "*****@*****.**"));
		        msg2.Subject = "subject2";
		        msg2.Body = new TextPart("plain") {Text = "body2"};

		        var emails =
		            (await
		                GetEmails(sut, s => s.GetEmails(), () => SendEmailsAsync(sut, msg), () => SendEmailsAsync(sut, msg2)))
		                .ToList();

		        Assert.That(emails.Count, Is.EqualTo(2));
		        AssertEmailsAreEqual(emails[0], msg2);
		        AssertEmailsAreEqual(emails[1], msg);
		    }
		}
예제 #9
0
    public async Task SendEmailAsync(SendMail mailRequest)
    {
        var email = new MimeKit.MimeMessage();

        email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
        email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
        email.Subject = mailRequest.Subject;
        var builder = new BodyBuilder();

        if (mailRequest.Attachments != null)
        {
            byte[] fileBytes;
            foreach (var file in mailRequest.Attachments)
            {
                if (file.Length > 0)
                {
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        fileBytes = ms.ToArray();
                    }
                    builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
                }
            }
        }
        builder.HtmlBody = mailRequest.Body;
        email.Body       = builder.ToMessageBody();
        using var smtp   = new SmtpClient();
        smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);
        smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
        await smtp.SendAsync(email);

        smtp.Disconnect(true);
    }
예제 #10
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);
     }
 }
예제 #11
0
        /// <summary>
        /// detects whether a message is a qmail (QSBMF) bounce message.
        /// </summary>
        ///
        /// See The qmail-send Bounce Message Format (QSBMF):
        ///      http://cr.yp.to/proto/qsbmf.txt
        public static BounceDetectResult Detect(MimeMessage message)
        {
            //
            // detect on a text part.

            var textPart = message.Body as TextPart;

            if (textPart != null)
            {
                var result = DetectQmailBounce(message, textPart);

                if (result != null)
                    return result;
            }

            //
            // detect on a multipart.

            var multipart = message.Body as MultipartAlternative;

            return multipart?
                .OfType<TextPart>()
                .Select(p => DetectQmailBounce(message, p))
                .FirstOrDefault();
        }
예제 #12
0
        public void CanReceive8BitMimeMessage()
        {
            // arrange
            var smtpServer     = new SmtpServer(_optionsBuilder.Build());
            var smtpClient     = new SmtpClient();
            var smtpServerTask = smtpServer.StartAsync(_cancellationTokenSource.Token);

            var message = new MimeKit.MimeMessage();

            message.From.Add(new MailboxAddress("*****@*****.**"));
            message.To.Add(new MailboxAddress("*****@*****.**"));
            message.Subject = "Assunto teste acento çãõáéíóú";
            message.Body    = new TextPart("plain")
            {
                Text = "Assunto teste acento çãõáéíóú"
            };

            // act
            smtpClient.Connect("localhost", 25, false);
            smtpClient.Send(message);

            // assert
            Assert.Equal(1, _messageStore.Messages.Count);

            Wait(smtpServerTask);
        }
예제 #13
0
        public static void TestSendMailDemo()
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MailboxAddress("Joey Tribbiani", "*****@*****.**"));
            message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "*****@*****.**"));
            message.Subject = "This is a Test Mail";
            var plain = new MimeKit.TextPart("plain")
            {
                Text = @"不好意思,我在测试程序,Sorry!"
            };

            // now create the multipart/mixed container to hold the message text and the
            // image attachment
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect("smtp.live.com", 587, false);

                // 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
                var mailFromAccount = "*****@*****.**";
                var mailPassword    = "******";
                client.Authenticate(mailFromAccount, mailPassword);

                client.Send(message);
                client.Disconnect(true);
            }
        }
예제 #14
0
        public static bool IsRuleMatching(MimeMessage message, Rule rule) {
            var fromAddress = message.From.Cast<MailboxAddress>().First().Address;

            switch (rule.Type) {
                case RuleType.SenderEquals:
                    return fromAddress == rule.Value;

                case RuleType.SenderContains:
                    return fromAddress.Contains(rule.Value);

                case RuleType.SenderEndsWith:
                    return fromAddress.EndsWith(rule.Value);

                case RuleType.SubjectContains:
                    return message.Subject.Contains(rule.Value);

                case RuleType.SubjectEquals:
                    return message.Subject == rule.Value;

                case RuleType.SubjectBeginsWith:
                    return message.Subject.StartsWith(rule.Value);

                case RuleType.SubjectEndsWith:
                    return message.Subject.EndsWith(rule.Value);
            }

            return false;
        }
예제 #15
0
파일: GMailService.cs 프로젝트: scovetta/AI
        // decode to mimeMessage
        public static MimeMessage DecodeToMessage(string text)
        {
            byte[]       msg = Base64UrlDecode(text);
            MemoryStream mm  = new MemoryStream(msg);

            MimeKit.MimeMessage mime = MimeKit.MimeMessage.Load(mm);
            return(mime);
        }
예제 #16
0
 public void EnviarAltaCuenta(string cuentaUsuario, string password)
 {
     var mensage = new MimeMessage();
     mensage.From.Add(new MailboxAddress("Verum In Sanguine", "*****@*****.**"));
     mensage.To.Add(new MailboxAddress(cuentaUsuario, cuentaUsuario));
     mensage.Subject = "Cuenta de usuario en Verum In Sanguine";
     mensage.Body = new TextPart("html") { Text = TextoAltaCuenta(cuentaUsuario, password) };
     EnviarMensaje(mensage);                       
 }
예제 #17
0
        /// <summary>
        /// Gets the email header as HTML
        /// </summary>
        /// <param name="message">The MIME message</param>
        /// <returns>The email headers as HTML</returns>
        public static string GetHtmlHeaders(MimeKit.MimeMessage message)
        {
            return($@"<div>
    <strong>Original Headers</strong>
</div>
<div>To: {string.Join(", ", message.To.Mailboxes.Select(m => m.Address))}</div>
<div>CC: {string.Join(", ", message.Cc.Mailboxes.Select(m => m.Address))}</div>
<hr/>");
        }
        private static void AnalyzeMessage(MimeMessage message, LearningDataSet result) {
            result.Adresses.AddOrIgnore(message?.Sender?.Address);
            result.Subjects.AddOrIgnore(message?.Subject);

            var urls = UrlParser.Parse(message?.TextBody);
            foreach (var url in urls) {
                result.Urls.AddOrIgnore(url);
            }
        }
예제 #19
0
 public async Task SendAsync(IdentityMessage message)
 {
     var mimeMessage = new MimeMessage();
     mimeMessage.From.Add(new MailboxAddress("Richard Benson", "*****@*****.**"));
     mimeMessage.To.Add(new MailboxAddress(message.Destination, message.Destination));
     mimeMessage.Subject = message.Subject;
     mimeMessage.Body = new TextPart("plain") { Text = message.Body };
     await _mailSender.SendMailAsync(mimeMessage);
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			webView.ScalesPageToFit = true;
			
			// Perform any additional setup after loading the view, typically from a nib.
			Message = MimeMessage.Load (GetType ().Assembly.GetManifestResourceStream ("xamarin3.msg"));
		}
예제 #21
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.MessageSentEventArgs"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MessageSentEventArgs"/>.
		/// </remarks>
		/// <param name="message">The message that was just sent.</param>
		/// <param name="response">The response from the server.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="message"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="response"/> is <c>null</c>.</para>
		/// </exception>
		public MessageSentEventArgs (MimeMessage message, string response)
		{
			if (message == null)
				throw new ArgumentNullException (nameof (message));

			if (response == null)
				throw new ArgumentNullException (nameof (response));

			Message = message;
			Response = response;
		}
예제 #22
0
        public MimeMessage CreateEmailMessage(string toEmailAddress = "", string toDisplayName = "", string fromEmailAddress = "", string fromDisplayName = "", string subject = "", string body = "")
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress(fromDisplayName, fromEmailAddress));
            emailMessage.To.Add(new MailboxAddress(toDisplayName, toEmailAddress));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart("plain") { Text = body };

            return emailMessage;
        }
예제 #23
0
		public MimeEntity Decrypt (MimeMessage message)
		{
			if (message.Body is MultipartEncrypted) {
				// the top-level MIME part of the message is encrypted using PGP/MIME
				var encrypted = (MultipartEncrypted) entity;

				return encrypted.Decrypt ();
			} else {
				// the top-level MIME part is not encrypted
				return message.Body;
			}
		}
예제 #24
0
		public static void SendMessage (MimeMessage message)
		{
			using (var client = new SmtpClient (new ProtocolLogger ("smtp.log"))) {
				client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);

				client.Authenticate ("username", "password");

				client.Send (message);

				client.Disconnect (true);
			}
		}
예제 #25
0
		public void MultipartSign (MimeMessage message)
		{
			// digitally sign our message body using our custom S/MIME cryptography context
			using (var ctx = new MySecureMimeContext ()) {
				// Note: this assumes that the Sender address has an S/MIME signing certificate
				// and private key with an X.509 Subject Email identifier that matches the
				// sender's email address.
				var sender = message.From.Mailboxes.FirstOrDefault ();

				message.Body = MultipartSigned.Create (ctx, sender, DigestAlgorithm.Sha1, message.Body);
			}
		}
예제 #26
0
		public MimeEntity Decrypt (MimeMessage message)
		{
			var pkcs7 = message.Body as ApplicationPkcs7Mime;

			if (pkcs7 != null && pkcs7.SecureMimeType == SecureMimeType.EnvelopedData) {
				// the top-level MIME part of the message is encrypted using S/MIME
				return pkcs7.Decrypt ();
			} else {
				// the top-level MIME part is not encrypted
				return message.Body;
			}
		}
예제 #27
0
		public void TestArgumentExceptions ()
		{
			var message = new MimeMessage ();

			Assert.Throws<ArgumentNullException> (() => new MessagePartial (null, 1, 5));
			Assert.Throws<ArgumentOutOfRangeException> (() => new MessagePartial ("id", 0, 5));
			Assert.Throws<ArgumentOutOfRangeException> (() => new MessagePartial ("id", 6, 5));
			Assert.Throws<ArgumentNullException> (() => new MessagePartial ("id", 1, 5).Accept (null));

			Assert.Throws<ArgumentNullException> (() => MessagePartial.Split (null, 500).ToList ());
			Assert.Throws<ArgumentOutOfRangeException> (() => MessagePartial.Split (message, 0).ToList ());
		}
예제 #28
0
 public void EnviarNuevoMensaje(string cuentaUsuario)
 {
     bool quiereEmail = _contexto.Users.Single(u => u.Email == cuentaUsuario).MailPorNotificacion;
     if (quiereEmail)
     {
         var mensage = new MimeMessage();
         mensage.From.Add(new MailboxAddress("Verum In Sanguine", "*****@*****.**"));
         mensage.To.Add(new MailboxAddress(cuentaUsuario, cuentaUsuario));
         mensage.Subject = "Cuenta de usuario en Verum In Sanguine";
         mensage.Body = new TextPart("html") { Text = TextoNuevoMensaje() };
         EnviarMensaje(mensage);
     }
 }
예제 #29
0
		MimeMessage CreateEightBitMessage ()
		{
			var message = new MimeMessage ();
			message.From.Add (new MailboxAddress ("Sender Name", "*****@*****.**"));
			message.To.Add (new MailboxAddress ("Recipient Name", "*****@*****.**"));
			message.Subject = "This is a test...";

			message.Body = new TextPart ("plain") {
				Text = "This is the message body with some unicode unicode: ☮ ☯"
			};

			return message;
		}
예제 #30
0
		public void Encrypt (MimeMessage message)
		{
			// encrypt our message body using our custom GnuPG cryptography context
			using (var ctx = new MyGnuPGContext ()) {
				// Note: this assumes that each of the recipients has a PGP key associated
				// with their email address in the user's public keyring.
				//
				// If this is not the case, you can use SecureMailboxAddresses instead of
				// normal MailboxAddresses which would allow you to specify the fingerprint
				// of their PGP keys. You could also choose to use one of the Encrypt()
				// overloads that take a list of PgpPublicKeys.
				message.Body = MultipartEncrypted.Encrypt (ctx, message.To.Mailboxes, message.Body);
			}
		}
예제 #31
0
		public void Encrypt (MimeMessage message)
		{
			// encrypt our message body using our custom S/MIME cryptography context
			using (var ctx = new MySecureMimeContext ()) {
				// Note: this assumes that each of the recipients has an S/MIME certificate
				// with an X.509 Subject Email identifier that matches their email address.
				//
				// If this is not the case, you can use SecureMailboxAddresses instead of
				// normal MailboxAddresses which would allow you to specify the fingerprint
				// of their certificates. You could also choose to use one of the Encrypt()
				// overloads that take a list of CmsRecipients, instead.
				message.Body = ApplicationPkcs7Mime.Encrypt (ctx, message.To.Mailboxes, message.Body);
			}
		}
예제 #32
0
		MimeMessage CreateBinaryMessage ()
		{
			var message = new MimeMessage ();
			message.From.Add (new MailboxAddress ("Sender Name", "*****@*****.**"));
			message.To.Add (new MailboxAddress ("Recipient Name", "*****@*****.**"));
			message.Subject = "This is a test...";

			message.Body = new TextPart ("plain") {
				Text = "This is the message body with some unicode unicode: ☮ ☯",
				ContentTransferEncoding = ContentEncoding.Binary
			};

			return message;
		}
        public async Task<Message> OpenTnef(StorageFile datFile)
        {
            var message = new MimeMessage();
            var bodyFile = default(StorageFile);
            var targetFilesCollection = new List<FileInfo>();
            using (var stream = await datFile.OpenStreamForReadAsync())
            {
                using (var tnefReader = new TnefReader(stream))
                {
                    message = ExtractTnefMessage(tnefReader);
                    if (message.Sender == null)
                    {
                        message.Sender = new MailboxAddress(string.Empty, "Sender unknown");
                    }

                    foreach (MimePart mimePart in message.Attachments)
                    {
                        var isoFile = await LastExtractedFilesProvider.WriteFileToIsoStorage(mimePart.FileName, mimePart.ContentObject.Open());
                        var basicProperties = await isoFile.GetBasicPropertiesAsync();
                        var thumb = this.GetVectorThumbnailByType(isoFile.FileType);
                        var size = FileSizeString((double)basicProperties.Size);
                        targetFilesCollection.Add(new FileInfo(isoFile, thumb, size, datFile.DisplayName));
                    }

                    var body = Enumerable.FirstOrDefault<TextPart>(Enumerable.OfType<TextPart>(message.BodyParts));
                    if (body != null && !String.IsNullOrEmpty(body.Text))
                    {
                        string bodyFileName = "Message_Body.";
                        if (body.IsHtml)
                        {
                            bodyFileName += "html";
                        }
                        else if (body.IsPlain)
                        {
                            bodyFileName += "txt";
                        }
                        else if (body.IsRichText)
                        {
                            bodyFileName += "rtf";
                        }

                        bodyFile = await LastExtractedFilesProvider.WriteFileToIsoStorage(bodyFileName, body.Text);
                    }
                }
            }

            var targetMessage = new Message(message.Subject, message.Sender.ToString(), string.Empty, message.Date.ToString(), bodyFile, targetFilesCollection);

            return targetMessage;
        }
예제 #34
0
        public async void SendMail(Recomendation recomendation, string templatePath, string runnerName)
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MimeKit.MailboxAddress("Mr Recomender", "*****@*****.**"));
            message.To.Add(new MimeKit.MailboxAddress("testMailBox", "*****@*****.**"));
            message.Subject = "Recomendation - " + recomendation.title + ". Delivered by: " + runnerName;

            var    bodyBuilder = new BodyBuilder();
            string templateContent;

            //TODO: investigate better way of cross platform file path resolving
            using (StreamReader SourceReader = System.IO.File.OpenText($"{templatePath}{Path.DirectorySeparatorChar}email.tmpl"))
            {
                templateContent = SourceReader.ReadToEnd();
            }
            StringBuilder myStringBuilder = new StringBuilder();

            myStringBuilder.Append("<h2>Here is a book recomendation, please enjoy</h2>");
            myStringBuilder.Append("<h3>Brought to you by our recomendations team!</h3>");
            myStringBuilder.Append("<dl>");
            myStringBuilder.Append("<dt>Title</dt>");
            myStringBuilder.Append($"<dd>{recomendation.title}</dd>");
            myStringBuilder.Append("<dt>Author</dt>");
            myStringBuilder.Append($"<dd>{recomendation.author}</dd>");
            myStringBuilder.Append("<dt>language</dt>");
            myStringBuilder.Append($"<dd>{recomendation.language}</dd>");
            myStringBuilder.Append("<dt>Page Count</dt>");
            myStringBuilder.Append($"<dd>{recomendation.pages}</dd>");
            myStringBuilder.Append("<dt>Wiki</dt>");
            myStringBuilder.Append($"<dd><a href='{recomendation.link}' />{recomendation.link}</dd>");
            myStringBuilder.Append("</dl>");

            bodyBuilder.HtmlBody = string.Format(templateContent,
                                                 GetStyleText(templatePath),
                                                 myStringBuilder.ToString()
                                                 );

            message.Body = bodyBuilder.ToMessageBody();

            using (var mailClient = new SmtpClient())
            {
                await mailClient.ConnectAsync(MAIL_HOST, MAIL_PORT, SecureSocketOptions.None);

                await mailClient.SendAsync(message);

                await mailClient.DisconnectAsync(true);
            }
        }
        /// <summary>
        /// detects whether a message is a standard bounce message.
        /// </summary>
        ///
        /// essentially this finds the `multipart/report; report-type=delivery-status` part and
        /// its `message/delivery-status` sub-part to decide whether a message is a bounce.
        ///
        /// the message/delivery-status mime part looks something like:
        ///
        ///      Content-Type: message/delivery-status
        ///
        ///      Reporting-MTA: dns; PTPEDGE02.test.local
        ///
        ///      Final-recipient: RFC822;
        ///       [email protected]
        ///      Action: failed
        ///      Status: 5.1.1
        ///      Remote-MTA: dns; mx.google.com
        ///      X-Supplementary-Info: &lt;mx.google.com #5.1.1 smtp;550-5.1.1 The email account
        ///       that you tried to reach does not exist.Please try 550-5.1.1 double-checking
        ///      the recipient's email address for typos or 550-5.1.1 unnecessary spaces.
        ///       Learn more at 550 5.1.1  https://support.google.com/mail/answer/6596
        ///       om11si19081667wic.29 - gsmtp>
        ///
        /// See the multipart/report format RFC:
        ///      The Multipart/Report Media Type for the Reporting of Mail System Administrative Messages
        ///      https://tools.ietf.org/html/rfc6522
        /// See the message/delivery-status RFC:
        ///      An Extensible Message Format for Delivery Status Notifications
        ///      https://tools.ietf.org/html/rfc3464
        public static BounceDetectResult Detect(MimeMessage message)
        {
            var visitor = new Visitor();

            message.Accept(visitor);

            var result = visitor.Result;

            return new BounceDetectResult(
                message,
                result.DeliveryNotificationPart,
                result.DeliveryStatus,
                result.UndeliveredMessagePart
            );
        }
예제 #36
0
파일: Email.cs 프로젝트: lynch251/SIMAIL
        // Retourne la template préremplie pour le mail de retour
        public string getReponseHeader(MimeKit.MimeMessage ms)
        {
            string str = "";

            if (ms != null & From != "" & Body != null)
            {
                str += "\r\n\r\n\r\n\r\n -------------------------------------------------------------------------------------------- \r";
                str += "De :" + ms.From + "\r";
                str += "Envoyé : " + ms.Date.DateTime.ToLocalTime().ToLongDateString() + "\r";
                str += "A : " + ms.To.ToString() + "\r";
                str += "Objet : " + ms.Subject + "\r";
                str += "\r" + Body.convertTextFromHtml(ms.HtmlBody);
            }
            return(str);
        }
예제 #37
0
        static async Task SendMessageAsync(SmtpClient smtpClient, string name, int counter, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MimeKit.MailboxAddress($"{name}{counter}@test.com"));
            message.To.Add(new MimeKit.MailboxAddress("*****@*****.**"));
            message.Subject = $"{name} {counter}";

            message.Body = new TextPart(TextFormat.Plain)
            {
                Text = ".Assunto teste acento çãõáéíóú"
            };

            await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
        }
        public ActionResult sendMail(string mail)
        {
            var ac = db.AUTHs.Find(mail);

            if (ac is null)
            {
                var result = new
                {
                    status  = false,
                    message = "username không tồn tại để được cập nhật lại mật khẩu"
                };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
            var msg = new MimeKit.MimeMessage();

            msg.From.Add(new MailboxAddress("Bạn Nụ Cute", "*****@*****.**"));
            msg.To.Add(new MailboxAddress("abc", mail));
            msg.Subject = "Pass";
            msg.Body    = new TextPart("plain")
            {
                Text = "https://*****:*****@gmail.com", "aqbook123");
                    client.Send(msg);
                    client.Disconnect(true);
                }
                var result = new
                {
                    status  = true,
                    message = "Gửi mail thành công"
                };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
            catch
            {
                var result = new
                {
                    status  = false,
                    message = "Không thể gửi mail được mong bạn check lại username"
                };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }
예제 #39
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);
                }
            }
        }
예제 #40
0
 public ProcessamentoEmail2(ConfiguracaoContasEmails configuracaoContaEmail, MimeMessage mailMessage,
                            string userId, IEmailServico emailServico, string diretorioArquivos, IAtividadeServico servicoAtividade,
                            IEmailServico servicoEmail, List <EmailRemetenteRegra> emailsSpamFila)
 {
     _configuracaoContaEmail = configuracaoContaEmail;
     _mensagem           = mailMessage;
     _identificadorAnexo = Guid.NewGuid();
     BootStrapper.ContainerServicoLeituraEmail();
     _emailServico      = emailServico;
     _anexos            = new List <EmailAnexo>();
     _diretorioArquivos = diretorioArquivos;
     _diretorioArquivos = @"C:\Users\ptd000068\Desktop\AnexosFTP";
     _servicoEmail      = servicoEmail;
     _envolvidos        = new List <AtividadeParteEnvolvida>();
     _emailsSpamFila    = emailsSpamFila;
 }
예제 #41
0
        ///<summary>Helper method that returns a ready-to-send Gmail Message</summary>
        private static GmailApi.Data.Message CreateGmailMsg(BasicEmailAddress emailAddress, BasicEmailMessage emailMessage)
        {
            MimeKit.MimeMessage mimeMsg = CreateMIMEMsg(emailAddress, emailMessage);
            using Stream stream = new MemoryStream();
            mimeMsg.WriteTo(stream);
            stream.Position       = 0;
            using StreamReader sr = new StreamReader(stream);
            GmailApi.Data.Message gMsg = new GmailApi.Data.Message();
            string rawString           = sr.ReadToEnd();

            byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
            gMsg.Raw = System.Convert.ToBase64String(raw);
            //What we send to Gmail must be a Base64 File/URL safe string.  We must convert our base64 to be URL safe. (replace - and _ with + and / respectively)
            gMsg.Raw = gMsg.Raw.Replace("+", "-");
            gMsg.Raw = gMsg.Raw.Replace("/", "_");
            return(gMsg);
        }
예제 #42
0
        public Task Execute(string subject, string message, string email)
        {
            var msg = new MimeKit.MimeMessage();

            msg.From.Add(new MailboxAddress("cocktails", this.userName));
            msg.To.Add(MailboxAddress.Parse(email));
            msg.Subject = subject;
            var builder = new BodyBuilder();

            builder.HtmlBody = message;
            msg.Body         = builder.ToMessageBody();

            var smtp = new SmtpClient();

            smtp.Connect(this.host, this.port, MailKit.Security.SecureSocketOptions.SslOnConnect);
            smtp.Authenticate(this.userName, this.password);
            return(smtp.SendAsync(msg));
        }
        public async void SendEmailToGmail(string subject, string From, string data)
        {
            GmailService gmailService = await GetGmailService();

            MailMessage mail = new MailMessage();

            mail.Subject    = subject;
            mail.Body       = data;
            mail.From       = new MailAddress(From);
            mail.IsBodyHtml = true;
            mail.To.Add(new MailAddress("*****@*****.**"));
            //mail.CC.Add(new MailAddress(CC));
            #region comments
            //foreach (string add in vendorEmailList.Split(','))
            //{
            //    if (string.IsNullOrEmpty(add))
            //        continue;

            //    mail.To.Add(new MailAddress(add));
            //}

            //foreach (string add in userEmailList.Split(','))
            //{
            //    if (string.IsNullOrEmpty(add))
            //        continue;

            //    mail.CC.Add(new MailAddress(add));
            //}

            //foreach (string path in attachments)
            //{
            //    //var bytes = File.ReadAllBytes(path);
            //    //string mimeType = MimeMapping.GetMimeMapping(path);
            //    Attachment attachment = new Attachment(path);//bytes, mimeType, Path.GetFileName(path), true);
            //    mail.Attachments.Add(attachment);
            //}
            #endregion
            MimeKit.MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(mail);
            Message             message     = new Message();
            var inputBytes = System.Text.Encoding.UTF8.GetBytes(mimeMessage.ToString());
            message.Raw = Convert.ToBase64String(inputBytes);
            var result = gmailService.Users.Messages.Send(message, From).Execute();
        }
예제 #44
0
        public async Task <JsonResult> GetMessage(string folderName, int id)
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            if (userId == null)
            {
                throw new ApplicationException($"User ID was not found in user claims!");
            }

            var user = await _dbContext.Users
                       .Include(appUser => appUser.ImapConfigurations)
                       .SingleOrDefaultAsync(appUser => appUser.Id == userId);

            // for now using only one configuration
            var firstImapConf = user.ImapConfigurations.First();

            if (!ImapClientModel.ImapClientModelsDictionary.TryGetValue(firstImapConf.Login + firstImapConf.Password, out var model))
            {
                model = new ImapClientModel(
                    firstImapConf.Login,
                    firstImapConf.Password,
                    firstImapConf.Host,
                    firstImapConf.Port,
                    firstImapConf.UseSsl);
            }

            folderName = WebUtility.UrlDecode(folderName);

            string activeFolder = folderName == null ? "INBOX" : folderName;

            MimeKit.MimeMessage message = model.GetMessage(activeFolder, (uint)id);
            var messageBody             = message.HtmlBody == null ? message.TextBody : message.HtmlBody;

            var data = new
            {
                Subject = message.Subject,
                From    = message.From.ToString(),
                Body    = messageBody
            };

            return(new JsonResult(data));
        }
예제 #45
0
        static async Task RunClientAsync(string name, int maximum = Int32.MaxValue, CancellationToken cancellationToken = default(CancellationToken))
        {
            var counter = 0;

            while (counter++ < maximum && cancellationToken.IsCancellationRequested == false)
            {
                using (var smtpClient = new SmtpClient())
                {
                    await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken);

                    Console.WriteLine();
                    Console.WriteLine("Client has Connected.");
                    Console.WriteLine(smtpClient.Capabilities);
                    Console.WriteLine(smtpClient.IsSecure);
                    Console.WriteLine();

                    try
                    {
                        var message = new MimeKit.MimeMessage();
                        message.From.Add(new MimeKit.MailboxAddress($"{name}{counter}@test.com"));
                        message.To.Add(new MimeKit.MailboxAddress("*****@*****.**"));
                        message.Subject = $"Subject test çãõáéíóú";

                        message.Body = new TextPart(TextFormat.Plain)
                        {
                            Text = "Test Message Body special char çãõáéíóú",
                        };

                        await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }

                    await smtpClient.DisconnectAsync(true, cancellationToken);
                }

                counter++;
            }
        }
예제 #46
0
파일: Program.cs 프로젝트: ccpu/SmtpServer
        static async Task RunClientAsync(string name, int limit = Int32.MaxValue, CancellationToken cancellationToken = default(CancellationToken))
        {
            var counter = 1;

            while (limit-- > 0 && cancellationToken.IsCancellationRequested == false)
            {
                using (var smtpClient = new SmtpClient())
                {
                    try
                    {
                        await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken);

                        await smtpClient.AuthenticateAsync("user", "password", cancellationToken);

                        var message = new MimeKit.MimeMessage();
                        message.From.Add(new MimeKit.MailboxAddress($"{name}{counter}@test.com"));
                        message.To.Add(new MimeKit.MailboxAddress("*****@*****.**"));
                        message.Subject = $"{name} {counter}";

                        message.Body = new TextPart(TextFormat.Plain)
                        {
                            //Text = ".Ad",
                            Text = ".Assunto teste acento çãõáéíóú",
                            //Text = "Assunto teste acento",
                        };

                        await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }

                    await smtpClient.DisconnectAsync(true, cancellationToken);
                }

                counter++;
            }
        }
예제 #47
0
 private void Send(MimeKit.MimeMessage mailMessage)
 {
     using (var client = new SmtpClient())
     {
         try
         {
             client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, true);
             client.AuthenticationMechanisms.Remove("XOAUTH2");
             client.Authenticate(_emailConfig.UserName, _emailConfig.Password);
             client.Send(mailMessage);
         }
         catch
         {
             //log an error message or throw an exception or both.
             throw;
         }
         finally
         {
             client.Disconnect(true);
             client.Dispose();
         }
     }
 }
예제 #48
0
        public static MimeMessage createEmail(string to, string from, string product)
        {
            string      path = productZipFolder;
            MailMessage mail = new MailMessage();

            mail.Subject = "Placeholder : Thanks for your support!";
            mail.Sender  = new MailAddress(senderEmail, senderName);

            MimeKit.MimeMessage messageToSend = MimeKit.MimeMessage.CreateFromMailMessage(mail);

            messageToSend.To.Add(new MailboxAddress(to));
            var body = new TextPart(TextFormat.Text)
            {
                Text = "Hi ☺\n\n" +
                       "Thanks for your support and hope you enjoy what we've created! \n\n" +
                       "Download and unzip the contents attached to find your purchase.\n\n" +
                       "Please respond to this email if you have any questions or face any issues. \n\n" +
                       "Thanking You,\n" +
                       "- Placeholder"
            };

            var attachment = new MimePart("image", "gif")
            {
                Content                 = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(path)
            };

            var multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(attachment);
            messageToSend.Body = multipart;

            return(messageToSend);
        }
예제 #49
0
        public static void SendEmail(String subject, String name, String receiverEmail, String sendMessage)
        {
            var message = new MimeKit.MimeMessage();

            message.From.Add(new MailboxAddress("Team18ams", "*****@*****.**"));
            message.To.Add(new MailboxAddress(name, receiverEmail));
            message.Subject = subject;
            message.Body    = new TextPart("plain")
            {
                Text = sendMessage
            };

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("smtp.gmail.com", 587, false);

                client.Authenticate("*****@*****.**", "hirelonghorn!");

                client.Send(message);
                client.Disconnect(true);
            }
        }
        public async Task SendEmailAsync(
            IEnumerable <string> to,
            IEnumerable <string> cc,
            IEnumerable <string> bcc,
            string subject,
            string body)
        {
            using (var gmailservice = await _googleSheetsServiceAccessor.GetGmailServiceAsync())
            {
                Boolean noReciver = true;
                System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
                var msg = new MailMessage()
                {
                    Subject    = subject,
                    Body       = body,
                    IsBodyHtml = true
                };

                foreach (var address in to)
                {
                    if (!string.IsNullOrEmpty(address))
                    {
                        noReciver = false;
                        msg.To.Add(new MailAddress(address));
                    }
                }
                foreach (var address in cc)
                {
                    if (!string.IsNullOrEmpty(address))
                    {
                        noReciver = false;
                        msg.CC.Add(new MailAddress(address));
                    }
                }
                foreach (var address in bcc)
                {
                    if (!string.IsNullOrEmpty(address))
                    {
                        noReciver = false;
                        msg.Bcc.Add(new MailAddress(address));
                    }
                }
                //foreach (string path in attachments)
                //{
                //    Attachment attachment = new Attachment(path);
                //    msg.Attachments.Add(attachment);
                //}

                if (noReciver != true)
                {
                    MimeKit.MimeMessage mimeMessage = MimeMessage.CreateFromMailMessage(msg);
                    Message             message     = new Message()
                    {
                        Raw = Base64UrlEncode(mimeMessage.ToString())
                    };
                    try
                    {
                        var result = gmailservice.Users.Messages.Send(message, "me").Execute();
                        _logger.Information("Just sent the email");
                    }
                    catch (Exception e)
                    {
                        _logger.Error("An error occurred: " + e.Message);
                    }
                }
                else if (noReciver == true)
                {
                    _logger.Warning("No recivers for this email");
                }
            }
        }
예제 #51
0
        public async Task <string> GetVerificationCode()
        {
            int started = Environment.TickCount;

            // email should not be older than 1 minute
            DateTime border = DateTime.Now.Subtract(TimeSpan.FromMinutes(1));

            await Task.Delay(initialWaitTime);

            string vcode = null;

            try
            {
                ImapClient client = new ImapClient();
                await client.ConnectAsync(Config.Host, Config.Port, MailKit.Security.SecureSocketOptions.Auto);

                await client.AuthenticateAsync(Config.Username, Config.Password);

                var inbox = await client.GetFolderAsync(Config.ImapFolderPath);

                List <MimeMessage>  msgList = null;
                MimeKit.MimeMessage mail    = null;

                while (mail == null)
                {
                    await inbox.OpenAsync(FolderAccess.ReadWrite);

                    // we need a list to determine the message's index reliably
                    msgList = inbox.ToList();
                    mail    = msgList.FirstOrDefault(x => x.From.Mailboxes.Any(f => f.Address.ToLower().Contains(Config.VerificationFromAddress.ToLower())) && x.Subject.Contains(Config.VerificationMailSubject) && x.Date >= border);
                    if (mail != null)
                    {
                        break;
                    }

                    // wait then retry
                    await inbox.CloseAsync();

                    if (Environment.TickCount - started > timeout.TotalMilliseconds)
                    {
                        throw new TimeoutException();
                    }
                    await Task.Delay(retryWaitTime);
                }

                string msg_content = mail.TextBody;
                vcode = ExtractVerificationCode(msg_content);

                // since we are going to use the VerificationCode, delete the message
                if (msgList != null)
                {
                    int midx = msgList.IndexOf(mail);
                    inbox.AddFlags(midx, MessageFlags.Deleted, true);
                    await inbox.ExpungeAsync();
                }

                await inbox.CloseAsync();

                await client.DisconnectAsync(true);
            }
            catch (Exception e)
            {
                // maybe we still got the verification code
            }

            // return what we have
            return(vcode);
        }
예제 #52
0
        /// <summary>
        /// Asynchronously parses a message from the stream.
        /// </summary>
        /// <remarks>
        /// Parses a message from the stream.
        /// </remarks>
        /// <returns>The parsed message.</returns>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.FormatException">
        /// There was an error parsing the message.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public async Task <MimeMessage> ParseMessageAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Note: if a previously parsed MimePart's content has been read,
            // then the stream position will have moved and will need to be
            // reset.
            if (persistent && stream.Position != position)
            {
                stream.Seek(position, SeekOrigin.Begin);
            }

            // scan the from-line if we are parsing an mbox
            while (state != MimeParserState.MessageHeaders)
            {
                switch (await StepAsync(cancellationToken).ConfigureAwait(false))
                {
                case MimeParserState.Error:
                    throw new FormatException("Failed to find mbox From marker.");

                case MimeParserState.Eos:
                    throw new FormatException("End of stream.");
                }
            }

            toplevel = true;

            // parse the headers
            var beginLineNumber = lineNumber;

            if (state < MimeParserState.Content && await StepAsync(cancellationToken).ConfigureAwait(false) == MimeParserState.Error)
            {
                throw new FormatException("Failed to parse message headers.");
            }

            var message     = new MimeMessage(options, headers, RfcComplianceMode.Loose);
            var messageArgs = new MimeMessageEndEventArgs(message)
            {
                HeadersEndOffset = headerBlockEnd,
                BeginOffset      = headerBlockBegin,
                LineNumber       = beginLineNumber
            };

            OnMimeMessageBegin(messageArgs);

            if (format == MimeFormat.Mbox && options.RespectContentLength)
            {
                contentEnd = 0;

                for (int i = 0; i < headers.Count; i++)
                {
                    if (headers[i].Id != HeaderId.ContentLength)
                    {
                        continue;
                    }

                    var value = headers[i].RawValue;
                    int index = 0;

                    if (!ParseUtils.SkipWhiteSpace(value, ref index, value.Length))
                    {
                        continue;
                    }

                    if (!ParseUtils.TryParseInt32(value, ref index, value.Length, out int length))
                    {
                        continue;
                    }

                    contentEnd = GetOffset(inputIndex) + length;
                    break;
                }
            }

            var type       = GetContentType(null);
            var entity     = options.CreateEntity(type, headers, true, 0);
            var entityArgs = new MimeEntityEndEventArgs(entity)
            {
                HeadersEndOffset = headerBlockEnd,
                BeginOffset      = headerBlockBegin,
                LineNumber       = beginLineNumber
            };

            OnMimeEntityBegin(entityArgs);

            message.Body = entity;

            if (entity is Multipart)
            {
                await ConstructMultipartAsync((Multipart)entity, entityArgs, 0, cancellationToken).ConfigureAwait(false);
            }
            else if (entity is MessagePart)
            {
                await ConstructMessagePartAsync((MessagePart)entity, entityArgs, 0, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                await ConstructMimePartAsync((MimePart)entity, entityArgs, cancellationToken).ConfigureAwait(false);
            }

            var endOffset = GetEndOffset(inputIndex);

            messageArgs.HeadersEndOffset = entityArgs.HeadersEndOffset = Math.Min(entityArgs.HeadersEndOffset, endOffset);
            messageArgs.EndOffset        = entityArgs.EndOffset = endOffset;

            if (boundary != BoundaryType.Eos)
            {
                if (format == MimeFormat.Mbox)
                {
                    state = MimeParserState.MboxMarker;
                }
                else
                {
                    state = MimeParserState.Complete;
                }
            }
            else
            {
                state = MimeParserState.Eos;
            }

            OnMimeEntityEnd(entityArgs);
            OnMimeMessageEnd(messageArgs);

            return(message);
        }
예제 #53
0
        public void BuildScheduledEmail(string queryName, string editUrl, string recipients, int queryId)
        {
            if (string.IsNullOrEmpty(recipients))
            {
                return;
            }

            if (!_emailSenderService.TrySetDelivered(queryId))
            {
                return;
            }

            var query = _db.Queries
                        .Include(q => q.DatabaseConnection)
                        .FirstOrDefault(q => q.QueryID == queryId);

            if (query != null && query.QueryDefinition != null)
            {
                var queryDefinition = JsonConvert.DeserializeObject <dynamic>(query.QueryDefinition);
                var nodes           = JsonConvert.SerializeObject(queryDefinition.Nodes);
                var selectedNodeId  = queryDefinition.SelectedNodeId.ToString();

                var data = _dbMgr.GetData(query.DatabaseConnection, nodes, selectedNodeId, null, null);

                var attachment = _convertManager.ToExcel(data);

                var message = new MimeKit.MimeMessage();

                foreach (var email in recipients.Split(','))
                {
                    message.To.Add(new MailboxAddress(email));
                }

                message.From.Add(new MailboxAddress("QueryTree", _config.GetValue <string>("Email:SenderAddress")));
                message.Subject = string.Format("Here's your scheduled report {0}", queryName);

                // load template
                string text = System.IO.File.ReadAllText(Path.Combine(_env.WebRootPath, @"../EmailTemplates/ScheduledReport.txt"));
                string html = System.IO.File.ReadAllText(Path.Combine(_env.WebRootPath, @"../EmailTemplates/ScheduledReport.html"));

                // set up replacements
                var replacements = new Dictionary <string, string>
                {
                    { "{reportname}", queryName },
                    { "{editurl}", editUrl }
                };

                // do replacement
                foreach (var key in replacements.Keys)
                {
                    text = text.Replace(key, replacements[key]);
                    html = html.Replace(key, replacements[key]);
                }

                var builder = new BodyBuilder();

                builder.TextBody = text;
                builder.HtmlBody = html;

                using (var stream = new MemoryStream(attachment))
                {
                    var fileName = queryName == null || queryName.Length == 0 ? "report" : queryName;
                    builder.Attachments.Add(string.Format("{0}.xlsx", fileName), stream);
                }

                message.Body = builder.ToMessageBody();

                _emailSender.SendMail(message);
            }
        }
예제 #54
0
 internal static void SetSubject(this MimeKit.MimeMessage mimeMessage, MailMessage mailMessage) =>
 mimeMessage.Headers.Replace(MimeKit.HeaderId.Subject, mailMessage.Encoding, mailMessage.Subject);
예제 #55
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var element = Utils.LoadConfigurationFromWebConfig("Google");
            var client  = new Google(
                element.ClientId,
                element.ClientSecret,
                element.Scope,
                element.RedirectUri);
            //var element = Utils.LoadConfigurationFromWebConfig("WindowsLive");
            //var client = new WindowsLive(element.ClientId, element.ClientSecret, element.Scope, element.RedirectUri);
            var client1 = new SmtpClient(new ProtocolLogger(@"c:\temp\smtp.log"));

            try
            {
                client.HandleAuthorizationCodeResponse();
                litAccessToken.Text = client.AccessToken;
                litState.Text       = client.GetStateObject(string.Empty).GetValue("one");
                var message = new MimeKit.MimeMessage();
                message.From.Add(new MailboxAddress("SK Dutta", "*****@*****.**"));
                //message.To.Add(new MailboxAddress("SK Dutta", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Kim Jung", "*****@*****.**"));
                message.Subject = "Test Subject 210010";
                message.Body    = new TextPart("plain")
                {
                    Text = @"Hey"
                };
                using (client1)
                {
                    client1.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);

                    var oauth2 = new SaslMechanismOAuth2("*****@*****.**", client.AccessToken);
                    client1.Authenticate(oauth2);

                    client1.Send(message);
                    client1.Disconnect(true);
                }
            }
            catch (Exception ex)
            {
                litError.Text = ex.Message;
                //litError.Text = client1.ProtocolLogger
                //return;
            }
            finally
            {
            }
            //try
            //{
            //    UserInfo userInfo = client.GetUserInfo();
            //    litFullName.Text = userInfo.FullName;
            //    litEmail.Text = userInfo.Email;
            //    ProfilePicture picture = new ProfilePicture(userInfo.PictureUrl, true);
            //    ImageHtml = picture.HtmlPart;
            //    picture.Resize(200);
            //    ImageResizedHtml = picture.HtmlPart;
            //    //DomainUsers googleDomainUsers = new DomainUsers(client.AccessToken);
            //    //litDirectoryString.Text = googleDomainUsers.ToJsonString();
            //}
            //catch (WebException webEx)
            //{
            //    HttpError httpError = new HttpError(webEx.Response);
            //    litError.Text = httpError.StatusDescription;
            //}
            //catch (Exception ex)
            //{
            //    litError.Text = ex.Message;
            //}

            //CalendarList calendarList = new CalendarList(client.AccessToken);
            //litCalendarString.Text = calendarList.ToJsonString();

            //ContactsGroup contactGroup = new ContactsGroup(client.AccessToken);
            //litContactString.Text = contactGroup.ToJsonString();
        }
예제 #56
0
        /// <summary>
        /// Splits the specified message into multiple messages.
        /// </summary>
        /// <remarks>
        /// Splits the specified message into multiple messages, each with a
        /// message/partial body no larger than the max size specified.
        /// </remarks>
        /// <returns>An enumeration of partial messages.</returns>
        /// <param name="message">The message.</param>
        /// <param name="maxSize">The maximum size for each message body.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="message"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="maxSize"/> is less than <c>1</c>.
        /// </exception>
        public static IEnumerable <MimeMessage> Split(MimeMessage message, int maxSize)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (maxSize < 1)
            {
                throw new ArgumentOutOfRangeException("maxSize");
            }

            using (var memory = new MemoryStream()) {
                message.WriteTo(memory);
                memory.Seek(0, SeekOrigin.Begin);

                if (memory.Length <= maxSize)
                {
                    yield return(message);

                    yield break;
                }

                var streams = new List <Stream> ();
#if !PORTABLE && !COREFX
                var buf = memory.GetBuffer();
#else
                var buf = memory.ToArray();
#endif
                long startIndex = 0;

                while (startIndex < memory.Length)
                {
                    // Preferably, we'd split on whole-lines if we can,
                    // but if that's not possible, split on max size
                    long endIndex = Math.Min(memory.Length, startIndex + maxSize);

                    if (endIndex < memory.Length)
                    {
                        long ebx = endIndex;

                        while (ebx > (startIndex + 1) && buf[ebx] != (byte)'\n')
                        {
                            ebx--;
                        }

                        if (buf[ebx] == (byte)'\n')
                        {
                            endIndex = ebx + 1;
                        }
                    }

                    streams.Add(new BoundStream(memory, startIndex, endIndex, true));
                    startIndex = endIndex;
                }

                var id     = message.MessageId ?? MimeUtils.GenerateMessageId();
                int number = 1;

                foreach (var stream in streams)
                {
                    var part = new MessagePartial(id, number++, streams.Count);
                    part.ContentObject = new ContentObject(stream);

                    var submessage = CloneMessage(message);
                    submessage.MessageId = MimeUtils.GenerateMessageId();
                    submessage.Body      = part;

                    yield return(submessage);
                }
            }

            yield break;
        }
예제 #57
0
 public MailPostMan()
 {
     this.MimeMessage = new MimeMessage();
     this.TextPart    = new TextPart();
 }
예제 #58
-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
		}
        public IActionResult Submit(ContactForm form)
        {
            if (!ModelState.IsValid)
                return View("Index", form);

            var emailMessage = new MimeMessage();

            var address = new MailboxAddress(Settings.Title, Settings.EmailFromAndTo);
            emailMessage.From.Add(address);
            emailMessage.To.Add(address);
            emailMessage.Subject = Settings.EmailSubject;
            var message = "Name: " + form.Name + Environment.NewLine
                + "Company: " + form.Company + Environment.NewLine
                + form.PreferredMethod + ": " + form.Email + form.Phone + Environment.NewLine
                + "Message:" + Environment.NewLine
                + form.Message;
            emailMessage.Body = new TextPart("plain") { Text = message };

            using (var client = new SmtpClient())
            {
                client.Connect(Settings.EmailServer, 465);
                client.Authenticate(Settings.EmailUser, Cache.Config["EmailPassword"]);
                client.Send(emailMessage);
                client.Disconnect(true);
            }
            return View("Thanks");
        }
예제 #60
-1
		public async Task SendMessage(MailAccount fromAccount, string messageText, params string[] receipients)
		{
			MimeKit.MimeMessage message = new MimeKit.MimeMessage();
			message.From.Add(fromAccount.Address);
			for (int i = 0; i < receipients.Length; i++)
			{
				message.To.Add (new MailboxAddress(receipients [i], receipients [i]));
			}

			message.Subject = string.Format("[OpenFlow {0}]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zz"));
			message.Body = new MimeKit.TextPart("plain") {
				Text = messageText
			};

			SmtpClient client = new SmtpClient();
			await client.ConnectAsync(fromAccount.SmtpAddress, fromAccount.SmtpPort, SecureSocketOptions.StartTls);
			try
			{
				client.AuthenticationMechanisms.Remove ("XOAUTH2");
				await client.AuthenticateAsync(fromAccount.Address.Address, fromAccount.Password);
				await client.SendAsync(message);
			}
			finally
			{
				await client.DisconnectAsync(true);	
			}
		}