Esempio n. 1
0
        static void send(string subject, User to)
        {
            try
            {
                MailBuilder builder = new MailBuilder();
                builder.Html    = @"Html with an image: <img src=""cid:lena"" />";
                builder.Subject = subject;


                MimeData visual = builder.AddVisual(HostingEnvironment.MapPath("~/Images/logo_2.png"));
                visual.ContentId = "lena";

                MimeData attachment = builder.AddAttachment(@"C:\Users\User\Desktop\Attachment.txt");
                attachment.FileName = "document.doc";

                builder.From.Add(new MailBox("*****@*****.**"));
                builder.To.Add(new MailBox(to.Email));
                //builder.To.Add(new MailBox("*****@*****.**"));
                IMail email = builder.Create();

                using (Smtp smtp = new Smtp())
                {
                    smtp.Connect(_server);       // or ConnectSSL for SSL
                    smtp.UseBestLogin(_user, _password);

                    smtp.SendMessage(email);

                    smtp.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 2
0
        private void SendMessageClick(object sender, RoutedEventArgs e)
        {
            MailBuilder builder = new MailBuilder();

            builder.From.Add(new MailBox(from_textBox.Text, "Hello"));
            builder.To.Add(new MailBox(to_textBox.Text, "World"));
            builder.Subject = subject_textBox.Text;
            builder.Text    = messageText_textBox.Text;

            IMail email = builder.Create();

            // отправка сообщения
            using (Smtp smtp = new Smtp())
            {
                smtp.ConnectSSL("smtp.gmail.com");
                smtp.UseBestLogin("email", "password"); //вставляем email и пароль

                ISendMessageResult result = smtp.SendMessage(email);
                if (result.Status == SendMessageStatus.Success)
                {
                    MessageBox.Show("Сообщение отправленно!");
                }
                smtp.Close();
            }
        }
Esempio n. 3
0
        public static void AddAttachment(this MailBuilder builder, IMail messageToAttach)
        {
            MimeRfc822 rfc822 = new MimeFactory().CreateMimeRfc822();

            rfc822.Data = messageToAttach.Render();
            builder.AddAttachment(rfc822);
        }
 private void updateMails(Flag selected)
 {
     using (Imap imap = new Imap())
     {
         listBox1.Items.Clear();
         imap.Connect("imap.mail.ru");   // or ConnectSSL for SSL
         imap.UseBestLogin(login, password);
         imap.SelectInbox();
         List <long> uids = imap.Search(selected);
         int         step = 0;
         foreach (long uid in uids)
         {
             if (step != 10)
             {
                 var   eml   = imap.GetMessageByUID(uid);
                 IMail email = new MailBuilder()
                               .CreateFromEml(eml);
                 listBox1.Items.Add(email.Subject + " " + email.Text);
                 step++;
             }
             else
             {
                 continue;
             }
         }
         imap.Close();
     }
 }
        public Form1(string login, string password)
        {
            InitializeComponent();
            myDictionary.Add("All", Flag.All);
            myDictionary.Add("Unseen", Flag.Unseen);
            myDictionary.Add("Answered", Flag.Answered);



            using (Imap imap = new Imap())
            {
                imap.Connect("imap.mail.ru"); // or ConnectSSL for SSL
                imap.UseBestLogin(login, password);
                imap.SelectInbox();
                List <long> uids = imap.Search(Flag.All);
                int         step = 0;
                foreach (long uid in uids)
                {
                    if (step != 10)
                    {
                        var   eml   = imap.GetMessageByUID(uid);
                        IMail email = new MailBuilder()
                                      .CreateFromEml(eml);
                        listBox1.Items.Add(email.Subject + " " + email.Text);
                        step++;
                    }
                    else
                    {
                        continue;
                    }
                }
                imap.Close();
            }
        }
        public Email GetMessageById(IMailboxSettings mailboxSettings, long emailId)
        {
            Email result = null;

            using (var imap = new Imap())
            {
                try
                {
                    var loggedIn = LoginToInbox(mailboxSettings, imap);

                    if (!loggedIn)
                        return null;

                    var eml = imap.PeekMessageByUID(emailId);
                    var email = new MailBuilder().CreateFromEml(eml);

                    result = EmailMapper.MapEmailToCoreEmail(mailboxSettings.AccountName, emailId, email);
                }
                catch (Exception ex)
                {
                    ApplyLabelToMessage(mailboxSettings, emailId, _mailboxLabels.InboundMailBoxErrorLabel);
                    MarkMessageAsRead(mailboxSettings, emailId);
                }
            }

            return result;
        }
        public void BaixarImap()
        {
            using (Imap imap = new Imap())
            {
                //imap.Connect("host sem SSL);
                imap.ConnectSSL(this.hostIMAP);
                imap.UseBestLogin(this.MeuEmaail, this.MinhaSenha);

                imap.SelectInbox();
                List <long> uids = imap.Search(Flag.All);

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder()
                                  .CreateFromEml(imap.GetMessageByUID(uid));

                    Console.WriteLine(email.Subject);

                    // salva anexo no disco
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(string.Concat(this.PathAnexo, mime.SafeFileName));
                    }
                }
            }
        }
Esempio n. 8
0
        private void DeleteEmails()
        {
            foreach (var account in LoadAccounts())
            {
                _logger.InfoFormat("Deleting emails from account: {0}", account.User);
                using (var client = new Pop3())
                {
                    client.Connect(_popHost, _popPort, _popUseSsl);
                    client.UseBestLogin(account.User, account.Password);

                    var stats = client.GetAccountStat();

                    long loopLimit = _batchSizePerAccount;
                    if (stats.MessageCount < loopLimit)
                        loopLimit = stats.MessageCount;

                    for (var i = 1; i <= loopLimit; i++)
                    {
                        var email = new MailBuilder().CreateFromEml(client.GetMessageByNumber(i));

                        if(email.Date.HasValue && 
                            DateTime.Now.Subtract(email.Date.Value).TotalDays > _deleteEmailsOlderThanDays)
                        {
                            client.DeleteMessageByNumber(i);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        private async void receiveMail()
        {
            using (Imap imap = new Imap())
            {
                await imap.ConnectSSL("imap.gmail.com");

                await imap.UseBestLoginAsync(USER, PASSWORD);

                await imap.SelectInboxAsync();

                List <long> uids = await imap.SearchAsync(Flag.Unseen);

                foreach (long uid in uids)
                {
                    var eml = await imap.GetMessageByUIDAsync(uid);

                    IMail mail = new MailBuilder().CreateFromEml(eml);
                    //Console.WriteLine(mail.Subject);
                    //Console.WriteLine(mail.Text);
                    string content = mail.Subject + " - " + mail.Text;
                    list.Items.Add(content);
                }
                await imap.CloseAsync();

                MessageDialog msg = new MessageDialog("Mail has been received");

                msg.ShowAsync();
            }
        }
        // this code is used for the SMTPAPI examples
        private static void Main()
        {
            // Create the email object first, then add the properties.
            SendGridMessage myMessage = MailBuilder.Create()
                                        .To("*****@*****.**")
                                        .From(new MailAddress("*****@*****.**", "John Smith"))
                                        .Subject("Testing the SendGrid Library")
                                        .Text("Hello World!")
                                        .Build();

            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential("username", "password");

            // Create a Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email.
            if (transportWeb != null)
            {
                transportWeb.DeliverAsync(myMessage);
            }

            Console.WriteLine("Done!");
            Console.ReadLine();
        }
Esempio n. 11
0
        public void get_data_message()
        {
            try
            {
                string resultado;
                // C#
                using (Imap imap = new Imap())
                {
                    //puerto 110

                    imap.Connect("imap.gmail.com", 993, true);   // conneccion a host con el puerto
                    imap.UseBestLogin("*****@*****.**", "Facturacion2016");
                    imap.SelectInbox();

                    List <long> uids = imap.Search(Flag.Unseen);

                    foreach (long uid in uids)
                    {
                        IMail email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(uid));

                        Console.WriteLine(email.Subject);
                        // guardar elementos en el disco
                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save("c:/tyscom xml/respuestas_sii/" + mime.SafeFileName);
                        }
                    }
                    imap.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                MailBuilder mb = new MailBuilder();
                mb.From.Add(new MailBox(txtFrom.Text));
                mb.To.Add(new MailBox(txtTo.Text));
                mb.Subject = txtSubject.Text;
                mb.Html    = txtBody.Text;
                if (file != null)
                {
                    await mb.AddAttachment(file);
                }

                IMail mail = mb.Create();
                try
                {
                    Smtp smtp = new Smtp();
                    await smtp.Connect("smtp.gmail.com", 587);

                    await smtp.UseBestLoginAsync(txtFrom.Text, txtPasscode.Password);

                    await smtp.SendMessageAsync(mail);

                    await smtp.CloseAsync();
                }
                catch (Exception ex)
                {
                    new MessageDialog(ex.Message).ShowAsync();

                    //throw;
                }
            }
            await new MessageDialog("Send mail completed").ShowAsync();
        }
        public static void SendPrize(CrossladderManagerhistoryEntity manager, EnumCrossLadderPrizeType crossLadderPrizeType, EnumMailType mailType, int seasonStatus)
        {
            if (string.IsNullOrEmpty(manager.PrizeItems))
            {
                manager.PrizeItems = "";
                MailBuilder mail = null;

                int packId = CacheFactory.CrossLadderCache.GetRankPrize(crossLadderPrizeType, manager.Rank,seasonStatus);
                if (packId <= 0)
                {
                    SystemlogMgr.Info("CrossLadderSendPrize", "no packid for rank:" + manager.Rank);
                    return;
                }
                mail = new MailBuilder(mailType, manager.ManagerId,manager.Season,manager.Rank,manager.RecordDate);
                var code = MallCore.Instance.BuildPackMail(packId, ref mail);
                if (code != MessageCode.Success)
                {
                    SystemlogMgr.Info("CrossLadderSendPrize", "build pack fail rank:" + manager.Rank + ",packId:" + packId);
                    return;
                }
                manager.PrizeItems = "pack:" + packId;
                manager.UpdateTime = DateTime.Now;
                try
                {
                    CrossladderManagerhistoryMgr.SavePrize(manager.Idx,manager.PrizeItems);
                    mail.Save(manager.SiteId);
                }
                catch (Exception ex)
                {
                    SystemlogMgr.Error("CrossLadderSendPrize", ex);
                }
            }
        }
Esempio n. 14
0
        private static void MailDLLExample()
        {
            using (Imap imap = new Imap())
            {
                //http://www.limilabs.com/mail/samples

                Console.WriteLine("Hello World");
                imap.Connect("imap.gmail.com",993,true);   // or ConnectSSL for SSL
                Console.WriteLine("SSL Connection Made");
                imap.UseBestLogin("USERNAME", "PASSWORD");
                Console.WriteLine("Login successful");

                imap.SelectInbox();
                List<long> uids = imap.Search(Flag.All);

                Console.WriteLine("Retrieved array of email id's");

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder()
                        .CreateFromEml(imap.GetMessageByUID(uid));

                    Console.WriteLine(email.Subject);

                    // save all attachments to disk
                    foreach (MimeData mime in email.Attachments)
                    {
                        mime.Save(mime.SafeFileName);
                    }
                }
                imap.Close();
            }
        }
Esempio n. 15
0
        public async Task <List <Email> > GetPop3EmailHeaders(Model.UserInfo userInfo)
        {
            Pop3 pop3 = await ConnectPop3(userInfo);

            try
            {
                if (pop3 != null)
                {
                    List <string> uids    = pop3.GetAll();
                    MailBuilder   builder = new MailBuilder();
                    foreach (string uid in uids)
                    {
                        var   headers = pop3.GetHeadersByUID(uid);
                        IMail mail    = builder.CreateFromEml(headers);

                        Email email = new Email
                        {
                            Uid     = uid,
                            Date    = mail.Date ?? DateTime.MinValue,
                            Subject = mail.Subject,
                            From    = string.Join(",", mail.From?.Select(s => s.Address)),
                        };
                        emailHeaderList.Add(email);
                    }
                }
                return(emailHeaderList);
            }
            finally
            {
                serverConnection.Add(pop3);
            }
        }
Esempio n. 16
0
        private void OpenMail(string mailPath, SaveMailToPdfRequest model)
        {
            InstantiateOutlook();

            string mailExt = Path.GetExtension(mailPath);

            if (mailExt.Equals(".msg", StringComparison.InvariantCultureIgnoreCase))
            {
                _logger.WriteInfo(new LogMessage(string.Concat("OpenMail -> item ", mailPath, " is .msg file. Open item with outlook directly.")), LogCategories);
                _outlookMail = OpenSharedItem(mailPath);
                return;
            }

            _logger.WriteInfo(new LogMessage(string.Concat("OpenMail -> item ", mailPath, " is not .msg file. Try build message manually.")), LogCategories);
            MailBuilder builder = new MailBuilder();
            IMail       mail    = builder.CreateFromEmlFile(mailPath);

            _outlookMail = ConvertToMsg(mail, model);

            if (_outlookMail == null)
            {
                _logger.WriteError(new LogMessage(string.Concat("OpenMail -> item ", mailPath, " not open. Check if item is a correct email message.")), LogCategories);
                throw new Exception("Mail not open. Check if item is a correct email message.");
            }
        }
Esempio n. 17
0
 static MessageCode doSendRankPrize(CrosscrowdInfoEntity crowd, CrosscrowdSendRankPrizeEntity entity, int maxPoint, int maxLegendCount)
 {
     try
     {
         if (entity.Status != 0)
         {
             return(MessageCode.Success);
         }
         if (entity.Score <= 0)
         {
             return(MessageCode.Success);
         }
         string      prizeItemString = "";
         var         mail            = new MailBuilder(entity.ManagerId, EnumMailType.CrossCrowdRank, entity.Rank);
         MessageCode mess            = BuildPrizeMail(crowd, mail, EnumCrowdPrizeCategory.CrossRank, entity.Rank, maxPoint, maxLegendCount, ref prizeItemString);
         if (mess != MessageCode.Success)
         {
             return(mess);
         }
         entity.Status = 1;
         CrosscrowdInfoMgr.SaveRankPrizeStatus(entity.Idx, entity.Status);
         if (!mail.Save(entity.SiteId))
         {
             return(MessageCode.NbParameterError);
         }
         SavePrizeRecord(entity.ManagerId, EnumCrowdPrizeCategory.CrossRank, "history:" + entity.Idx,
                         prizeItemString, entity.SiteId);
     }
     catch (Exception ex)
     {
         SystemlogMgr.Error("CrossCrowd-doSendRankPrize", ex);
         return(MessageCode.NbParameterError);
     }
     return(MessageCode.Success);
 }
Esempio n. 18
0
        public void filllistview()
        {
            MailListView.View          = View.Details;
            MailListView.GridLines     = true;
            MailListView.FullRowSelect = true;
            MailListView.Items.Clear();


            User user = User.Load("User.xml");

            using (Imap imap = new Imap())
            {
                imap.ConnectSSL("imap.gmail.com");
                imap.UseBestLogin(user.username, user.password);
                imap.SelectInbox();
                List <long> uids = imap.Search(sorter);
                foreach (long uid in uids)
                {
                    var   eml  = imap.GetMessageByUID(uid);
                    IMail mail = new MailBuilder().CreateFromEml(eml);

                    string[]     newMail = new string[5];
                    ListViewItem itm;
                    newMail[0] = mail.Sender.Name.ToString();
                    newMail[1] = mail.Date.ToString();
                    newMail[2] = mail.Subject.ToString();
                    newMail[3] = mail.Text.ToString();
                    newMail[4] = mail.Sender.Address.ToString();
                    itm        = new ListViewItem(newMail);
                    MailListView.Items.Add(itm);
                }
                imap.Close();
            }
        }
Esempio n. 19
0
        public bool SendEmailConfirmationLink(WebUser user)
        {
            if (user == null)
            {
                return(false);
            }

            string link = GenerateRandomLink();

            if (_userRepository.AddConfirmationKey(user, link, ConfirmType.EmailConfirmation))
            {
                string completeLink = _clientUrl + "/account/verify/" + link;
                using MailBuilder builder = new MailBuilder(_configuration);
                MailConfirmEmail model = new MailConfirmEmail
                {
                    FirstName = user.Firstname,
                    LastName  = user.Lastname,
                    Link      = completeLink,
                    To        = user.Email,
                    Type      = EmailKind.EmailConfirmation
                };
                var msg = builder.CreateMailConfirmEmail(model);
                builder.Dispose();
                return(_mailService.Send(msg));
            }
            Logger.LogInformation("Could not save confirmation link {link} for user {user}", link, user);
            return(false);
        }
Esempio n. 20
0
        public async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            MailBuilder myMail = new MailBuilder();
            myMail.Html = problem.Text;
            myMail.Subject = subject.Text;

           
            myMail.To.Add(new MailBox(txtemail.Text));
            myMail.From.Add(new MailBox(subject.Text));
         

            IMail email = myMail.Create();

            try
            {
                using (Smtp smtp = new Smtp())
                {
                    await smtp.Connect("smtp.mail.yahoo.com.hk",465);
                    await smtp.UseBestLoginAsync("*****@*****.**", "tyive123");
                    await smtp.SendMessageAsync(email);
                    await smtp.CloseAsync();
                    MessageDialog msg = new MessageDialog("Mail has been sucessfully sent");
                    await msg.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                MessageDialog msg = new MessageDialog("Mail has been sucessfully sent");
                msg.ShowAsync();
            }
        }
Esempio n. 21
0
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.ConnectSSL(_server);                        // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);                    // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                                 // or use UseBestLogin method if you want Mail.dll to choose for you.

                imap.SelectInbox();                              // You can select other folders, e.g. Sent folder: imap.Select("Sent");

                List <long> uids = imap.Search(Flag.Unseen);     // Find all unseen messages.

                Console.WriteLine("Number of unseen messages is: " + uids.Count);
                System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();

                synth.SetOutputToDefaultAudioDevice();
                String speak = "you have" + uids.Count.ToString();
                // Speak a string.
                synth.Speak(speak);

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        imap.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                imap.Close();
            }
        }
Esempio n. 22
0
        public async Task <RequestResult> RegistrarNovoUser(RegistroUserViewModel registroUserViewModel)
        {
            var registrarNovoUserCommand = registroUserViewModel.Map(new RegistrarNovoUserCommand());

            var result = await _bus.SendCommand(registrarNovoUserCommand);

            if (!result.isValid)
            {
                return(result);
            }

            var mailVariables = new Dictionary <string, string>
            {
                { "#USUARIONOME", registroUserViewModel.Nome },
                { "#USUARIOEMAIL", registroUserViewModel.Email }
            };

            var message = new MailMessage();

            message.To.Add(registroUserViewModel.Email);

            var mailBuilder = new MailBuilder(message, _configuration);
            var mailResult  = mailBuilder.PreparaTemplate("Confirmação de Cadastro", "ConfirmarCadastro", mailVariables);


            new MailService(mailResult, _configuration).Send();

            return(result);
        }
Esempio n. 23
0
        public void StartExample()
        {
            Mail mail = new MailBuilder()
                        .WithAddress(new AddressBuilder()
                                     .WithCity("New York")
                                     .WithCountry("USA")
                                     .WithHouse("34")
                                     .WithStreet("Brooklyn St."))
                        .WithFrom(new AddressantBuilder()
                                  .WithPostOffice(new PostOfficeBuilder()
                                                  .WithName("Post Office 1")
                                                  .WithAddress(new AddressBuilder()
                                                               .WithCountry("Germany")
                                                               .WithCity("Berlin")
                                                               .WithHouse("22e")
                                                               .WithStreet("Reinhardtstraße")))
                                  .WithPerson(new PersonBuilder()
                                              .WithFirstName("Frida")
                                              .WithSurname("Ultz")))
                        .WithTo(new AddressantBuilder()
                                .WithPostOffice(new PostOfficeBuilder()
                                                .WithName("Post Office 2")
                                                .WithAddress(new AddressBuilder()
                                                             .WithCountry("USA")
                                                             .WithCity("New York")
                                                             .WithHouse("15")
                                                             .WithStreet("Broome St.")))
                                .WithPerson(new PersonBuilder()
                                            .WithFirstName("James")
                                            .WithSecondName("Raph")
                                            .WithSurname("Steevenson")));

            Console.WriteLine(mail.ToString());
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            while (true)
            {
                using (Imap imap = new Imap())
                {
                    imap.ConnectSSL("imap.gmail.com"); // or ConnectSSL for SSL
                    imap.UseBestLogin(Email, PW);

                    imap.SelectInbox();
                    List <long> uidList = imap.Search(Flag.Unseen);
                    foreach (long uid in uidList)
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(imap.GetMessageByUID(uid));
                        string ExpressionToMatch = "hej";
                        if (Regex.IsMatch(email.Text, ExpressionToMatch))
                        {
                            SendEmail("i can see that your mail contained: " + ExpressionToMatch, email.ReturnPath);
                        }
                        Console.WriteLine(email.Text);
                        Console.WriteLine(email.ReturnPath);
                        Console.WriteLine(
                            "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////");
                    }

                    //Console.WriteLine("done press a key");
                    //Console.ReadKey();
                    //imap.Noop();
                    imap.Close();
                }
                Thread.Sleep(1000 * 10);
            }
        }
Esempio n. 25
0
        public bool SendResetPasswordMail(string email)
        {
            var randomLink = GenerateRandomLink();

            if (_userRepository.CheckIfEmailExists(email))
            {
                var user = _userRepository.TryGetUserByEmail(email);
                if (_userRepository.AddConfirmationKey(user, randomLink, ConfirmType.PasswordReset, DateTime.Now.AddHours(1)))
                {
                    string completeLink = _configuration.GetSection("Links").GetValue <string>("PasswordReset") + "/" + randomLink;
                    using MailBuilder builder = new MailBuilder(_configuration);
                    MailConfirmEmail model = new MailConfirmEmail
                    {
                        FirstName = user.Firstname,
                        LastName  = user.Lastname,
                        Link      = completeLink,
                        To        = user.Email,
                        Type      = EmailKind.PasswordReset
                    };
                    var msg = builder.CreateMailConfirmEmail(model);
                    return(_mailService.Send(msg));
                }
                return(false);
            }
            else
            {
                using MailBuilder builder = new MailBuilder(_configuration);
                return(_mailService.Send(builder.CreateUserDoesNotExistMail(email)));
            }
        }
Esempio n. 26
0
        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            MailBuilder myMail  = new MailBuilder();
            string      message = string.Empty;

            txtMessage.Document.GetText(Windows.UI.Text.TextGetOptions.AdjustCrlf, out message);
            myMail.Html    = message;
            myMail.Subject = txtSubject.Text;
            await myMail.AddAttachment(AttachFile);

            myMail.To.Add(new MailBox(txtTo.Text));
            myMail.From.Add(new MailBox(txtFrom.Text));
            myMail.Cc.Add(new MailBox(txtCC.Text));
            myMail.Bcc.Add(new MailBox(txtBCc.Text));
            IMail email = myMail.Create();

            using (Smtp smtp = new Smtp())
            {
                await smtp.Connect("smtp.gmail.com", 587);

                await smtp.UseBestLoginAsync("*****@*****.**", "Osxunix97");

                await smtp.SendMessageAsync(email);

                await smtp.CloseAsync();

                await new MessageDialog("mail send success").ShowAsync();
            }
        }
        public Task BeginDownloadInboxAsync(CancellationToken token)
        {
            return(Task.Factory.StartNew(() =>
            {
                using (var pop3 = new Pop3())
                {
                    ConnectAndLogin(pop3);
                    var allUids = pop3.GetAll();
                    var chunkUids = Common.SplitList(allUids, 5);
                    var builder = new MailBuilder();

                    foreach (var uids in chunkUids)
                    {
                        var items = new List <EmailItem>();
                        foreach (var uid in uids)
                        {
                            var bytes = pop3.GetHeadersByUID(uid);
                            IMail email = builder.CreateFromEml(bytes);
                            items.Add(ParseIMail(uid, email));
                        }
                        ItemsDownloaded?.Invoke(this, items);
                    }
                }
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default));
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var emailMessage = new MailBuilder().CreateFromEmlFile("635665579502893610.eml");

            Console.WriteLine(emailMessage.RenderEml(true));
            Console.ReadKey();
        }
Esempio n. 29
0
        public static void DownloadAttachmentFromMail()
        {
            try
            {
                using (Imap imap = new Imap())
                {
                    imap.Connect("imap.gmail.com", 993);
                    imap.UseBestLogin("*****@*****.**", "password");

                    imap.SelectInbox();
                    List <long> uids = imap.Search(Flag.All);

                    foreach (long uid in uids)
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(imap.GetMessageByUID(uid));
                        if (ColumnConfiguration.ProviderColumnName.ContainsKey(email.From.ToString()) &&
                            email.Date == DateTime.Now.Date)
                        {//Если есть поставщик в списке наименований колонок
                            Console.WriteLine(email.Subject);

                            foreach (MimeData mime in email.Attachments)
                            {
                                mime.Save(mime.SafeFileName);
                            }
                        }
                    }
                    imap.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 public override BodyModel GetBody(object uid)
 {
     if (uid is string)
     {
         if (pop3Connection != null)
         {
             MailBuilder builder = new MailBuilder();
             var headers = pop3Connection.GetMessageByUID(uid as string);
             IMail email = builder.CreateFromEml(headers);
             if (!string.IsNullOrWhiteSpace(email.Html))
             {
                 return BodyModel.GetHtmlBody(email.Html);
             }
             else if (!string.IsNullOrWhiteSpace(email.Text))
             {
                 return BodyModel.GetTextBody(email.Text);
             }
         }
     }
     else
     {
         //TODO: error handling
     }
     return null;
 }
Esempio n. 31
0
        /// <summary>
        /// Get mail using POP3 Mail Protocol
        /// </summary>
        /// <param name="folderName">Current Folder / Name of DataTable</param>
        /// <param name="emailCount">Count of email in folder</param>
        /// <param name="increment">Current Index</param>
        /// <param name="worker">BackgroundWorker that started this thread</param>
        private void GetMailUsingPOP3(string folderName, int increment, BackgroundWorker worker)
        {
            List <string> emails = _pop3.GetAll();

            foreach (string uid in emails)
            {
                // If top 5 perfect of emails, then download.
                if (float.Parse(uid) >= 42000f)
                {
                    // Add new row to DataTable
                    DataRow emailDataRow = _emailDataTableList[increment].NewRow();

                    IMail emailData = new MailBuilder()
                                      .CreateFromEml(_pop3.GetMessageByUID(uid));
                    // This takes just as long cause it downloads entire messages either way
                    emailDataRow["GUID"]    = uid;
                    emailDataRow["Date"]    = emailData.Date.ToString();
                    emailDataRow["From"]    = emailData.From;
                    emailDataRow["Body"]    = emailData.GetBodyAsHtml();
                    emailDataRow["Subject"] = emailData.Date.ToString() + " - " + emailData.Subject;
                    emailDataRow["Viewed"]  = 0;

                    _emailDataTableList[increment].Rows.Add(emailDataRow);
                }
            }
            _emailContent.Tables.Add(_emailDataTableList[increment]); //add data table if there is none in DS yet.
            _emailContent.Tables.Remove(folderName);
        }
Esempio n. 32
0
        public void GetAllMails(IProgress <IMail> progress, [Optional] FolderInfo folder)
        {
            using (Imap imap = new Imap())
            {
                imap.ConnectSSL(mailServer);
                imap.UseBestLogin(userData.UserMail, userData.Password);

                if (folder == null)
                {
                    imap.SelectInbox();
                }
                else
                {
                    imap.Select(folder);
                }

                List <long> uids = imap.Search(Flag.Unseen);
                NoofMails = uids.Count;
                foreach (long uid in uids)
                {
                    var   eml  = imap.GetMessageByUID(uid);
                    IMail mail = new MailBuilder().CreateFromEml(eml);

                    progress.Report(mail);
                }
                imap.Close();
            }
        }
Esempio n. 33
0
        private void buttonClientPop_Click(object sender, EventArgs e)
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect("mail.invoicedigital.cl");       // or ConnectSSL for SSL
                pop3.UseBestLogin("*****@*****.**", "sctgermany2016");

                foreach (string uid in pop3.GetAll())
                {
                    // verifico si existe el uid en la base
                    Console.WriteLine("Message unique-id: {0};", uid);
                    string nomArchivo = string.Empty;
                    if (descargaModel.exist(uid) == "False")
                    {
                        IMail email = new MailBuilder()
                                      .CreateFromEml(pop3.GetMessageByUID(uid));

                        Console.WriteLine("===================================================");
                        Console.WriteLine(email.Subject);
                        Console.WriteLine(email.Text);

                        foreach (MimeData mime in email.Attachments)
                        {
                            mime.Save(@"C:\AdmToSii\file\xml\proveedores\" + mime.SafeFileName);
                            nomArchivo = mime.SafeFileName;
                        }
                        Console.WriteLine("===================================================");
                        descargaModel.uid        = uid;
                        descargaModel.nomArchivo = nomArchivo;
                        descargaModel.save(descargaModel);
                    }
                }
                pop3.Close();
            }
        }
Esempio n. 34
0
        public MessageCode RefreshStatus()
        {
            DateTime date = DateTime.Now;

            foreach (var item in _transferDic.Values)
            {
                if (date >= item.TransferDuration)
                {
                    item.Status = 3;//流拍。 从数据库删除
                    if (TransferMainMgr.Delete(item.TransferId))
                    {
                        var mail = new MailBuilder(item.SellId, item.ItemCode, item.ItemName, EnumMailType.TransferRunOff);
                        if (!mail.Save(item.SellZoneName))
                        {
                            SystemlogMgr.Error("邮件发送失败",
                                               "邮件发送失败,ManagerId:" + item.SellId + ",ZoneName:" + item.SellZoneName + ",ItemCode:" +
                                               item.ItemCode);
                        }
                        Remove(item.TransferId);
                    }
                }
            }
            foreach (var entity in _tenTransferList)
            {
                //过了10分钟的放到另外一个字典
                if (entity.TransferStartTime.AddMinutes(10) < date)
                {
                    _transferDic.TryAdd(entity.TransferId, entity);
                }
            }
            _tenTransferList = _tenTransferList.FindAll(r => r.TransferStartTime.AddMinutes(10) > date);
            Sort();
            return(MessageCode.Success);
        }
Esempio n. 35
0
        int SendItemByType(NbManagershareEntity shareEntity, List <ConfigMallgiftbagEntity> prizeList)
        {
            if (prizeList.Count <= 0)
            {
                return((int)MessageCode.NbParameterError);
            }
            var mail = new MailBuilder(shareEntity.ManagerId, "分享礼包", 0, prizeList, EnumMailType.Share, 0, 0);

            //    var mail = new MailBuilder(shareEntity.ManagerId, point, coin, itemList, EnumMailType.Share);
            using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault()))
            {
                transactionManager.BeginTransaction();
                var f = true;
                if (!mail.Save(transactionManager.TransactionObject))
                {
                    f = false;
                }

                if (!NbManagershareMgr.Update(shareEntity, transactionManager.TransactionObject))
                {
                    f = false;
                }
                if (f)
                {
                    transactionManager.Commit();
                }
                else
                {
                    transactionManager.Rollback();
                    return((int)MessageCode.Exception);
                }
            }
            return((int)MessageCode.Success);
        }
Esempio n. 36
0
        void ConnectToEmail()
        {
            using (Imap ourImap = new Imap())
            {
                TextBoxOfMessages.Text += "       Соединение установлено" + "\r\n";
                ourImap.Connect("imap.***.ru");
                ourImap.Login("YourMail", "MailPassword");
                ourImap.Select("Спам");

                spamMessagesList        = ourImap.Search(Flag.All);
                TextBoxOfMessages.Text += "Писем в папке \"Спам\" : " + spamMessagesList.Count + "\r\n";

                foreach (long id in spamMessagesList)
                {
                    IMail email = new MailBuilder().CreateFromEml(ourImap.GetMessageByUID(id));
                    CleanFromSymbols(email.Text); // убрал email.Subject т.к. кривые символы
                }

                ourImap.SelectInbox();
                inputMassageList        = ourImap.Search(Flag.Flagged);
                TextBoxOfMessages.Text += "Отмечено писем : " + inputMassageList.Count + "\r\n";

                ourImap.Close();
            }
        }
Esempio n. 37
0
        private void EmailList_SelectedIndexChanged(object sender, EventArgs e)
        {
            long emailUID = Convert.ToInt64(EmailList.SelectedItem);

            var eml = imap.GetMessageByUID(emailUID);
            IMail email = new MailBuilder().CreateFromEml(eml);

            Subject.Text = email.Subject.ToString();
            Sender.Text = email.Sender.ToString();
            Body.Text = email.GetTextFromHtml().ToString();
        }
 public override EnvelopeModel GetEnvelope(object uid)
 {
     if(uid is string)
     {
         if (pop3Connection != null)
         {
             MailBuilder builder = new MailBuilder();
             var headers = pop3Connection.GetHeadersByUID(uid as string);
             IMail email = builder.CreateFromEml(headers);
             return new EnvelopeModel(email, uid as string);
         }
     }
     else
     {
         //TODO: error handling
     }
     return null;
 }
Esempio n. 39
0
        private void Process()
        {
            var builder = new MailBuilder();
            var enumerator = new WindowsLiveEmlEnumerator(_accountProvider).EnumerateFiles();

            foreach (var emlItem in enumerator)
            {
                _logger.InfoFormat("Parse EML File: {0}", emlItem.EmlFileName);

                try
                {
                    var eMail = builder.CreateFromEmlFile(emlItem.EmlFileName);
                    var processor = _emailProcessor.FirstOrDefault(p => p.LoadMail(eMail, emlItem.Folder));

                    if (processor != null)
                    {
                        try
                        {
                            processor.Publish(_publisher);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("PARSER_ENGINE_ERROR_SEND_TO_QUEUE", ex);
                        }
                    }

                    try
                    {
                        File.Delete(emlItem.EmlFileName);
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorFormat("Error deleting Eml File: {1} {0}", ex, emlItem.EmlFileName);
                    }
                }
                catch (Exception e)
                {
                    _logger.ErrorFormat("PARSER ERROR Parsing Eml File: {1} {0}", e, emlItem.EmlFileName);
                    continue;
                }

            }
        }
Esempio n. 40
0
        static void Main()
        {
            using (Pop3 pop3 = new Pop3())
            {
                pop3.Connect(_server);                      // Use overloads or ConnectSSL if you need to specify different port or SSL.
                pop3.Login(_user, _password);               // You can also use: LoginAPOP, LoginPLAIN, LoginCRAM, LoginDIGEST methods,
                                                            // or use UseBestLogin method if you want Mail.dll to choose for you.

                List<string> uidList = pop3.GetAll();       // Get unique-ids of all messages.

                foreach (string uid in uidList)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        pop3.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                pop3.Close();
            }
        }
Esempio n. 41
0
        private static void GetUnseenEmails(Imap imap)
        {
            imap.SelectInbox();

            List<long> uids = imap.SearchFlag(Flag.Unseen);

            int counterMails = 1;
            int totalMails = uids.Count;

            foreach (long uid in uids)
            {
                string eml = imap.GetMessageByUID(uid);
                IMail email = new MailBuilder().CreateFromEml(eml);

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine(email.Subject);
                Console.WriteLine(email.Text);

            }
        }
        public static IMail MapToIMail(Email message)
        {
            var builder = new MailBuilder();

            ProcessEmailAddresses(builder, message.EmailAddresses);

            builder.Subject = message.Subject;
            builder.Text = message.PlainTextBody;
            builder.PriorityHigh();

            if (!string.IsNullOrEmpty(message.HtmlBody))
                builder.Html = message.HtmlBody;

            foreach (var ea in message.Attachments)
            {
                var attachment = builder.AddAttachment(ea.ByteArray);
                attachment.FileName = ea.AttachmentName;
                attachment.ContentType = ContentType.Parse(ea.MimeType);
            }

            return builder.Create();
        }
Esempio n. 43
0
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.Connect(_server);                              // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);                       // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                                    // or use UseBestLogin method if you want Mail.dll to choose for you.

                imap.SelectInbox();                                 // You can select other folders, e.g. Sent folder: imap.Select("Sent");

                List<long> uids = imap.SearchFlag(Flag.Unseen);     // Find all unseen messages.
                
                Console.WriteLine("Number of unseen messages is: " + uids.Count);

                foreach (long uid in uids)
                {
                    IMail email = new MailBuilder().CreateFromEml(  // Download and parse each message.
                        imap.GetMessageByUID(uid));

                    ProcessMessage(email);                          // Display email data, save attachments.
                }
                imap.Close();
            }
        }
Esempio n. 44
0
        static void Main(string[] args)
        {
            using (Imap imap = new Imap())
            {
                //http://www.limilabs.com/mail/samples

                if (args.Length != 5)
                {
                    Console.WriteLine("Please run the executable with the following args:");
                    Console.WriteLine(
                        "Exchange Username Password DestinationFolderForAttachments DeleteEmailAfterDownloading");
                    Console.WriteLine();
                    Console.WriteLine("Eg 'bla.exe imap.gmail.com username password c:\temp 1");
                    Console.ReadKey();

                }
                else
                {
                    var mailserver = args[0];
                    var account = args[1];
                    var password = args[2];
                    var fileDest = args[3];
                    var DeleteEmail = args[4];

                    Console.WriteLine("Hello World");
                    imap.Connect(mailserver,993,true);   // or ConnectSSL for SSL
                    Console.WriteLine("SSL Connection Made");
                    imap.UseBestLogin(account, password);
                    Console.WriteLine("Login successful");

                    imap.SelectInbox();
                    List<long> uids = imap.Search(Flag.All);

                    Console.WriteLine("Retrieved array of email id's");

                    foreach (long uid in uids)
                    {
                        IMail email = new MailBuilder()
                            .CreateFromEml(imap.GetMessageByUID(uid));

                        Console.WriteLine("Retrieved email from " + email.Date);

                        // save all attachments to disk
                        foreach (MimeData mime in email.Attachments)
                        {
                            Console.WriteLine("Saving: " + mime.SafeFileName + " in " + fileDest);
                            mime.Save(fileDest + "\\" + mime.SafeFileName);
                        }

                        if (DeleteEmail == "1")
                        {
                            Console.WriteLine("Deleting email : " + email.Date);
                            imap.DeleteMessageByUID(uid);
                        }

                    }
                    imap.Close();
                }

            }
        }
Esempio n. 45
0
        public void ParseEmlFiles(CancellationToken token)
        {

            var emails = new DirectoryInfo(Settings.WorkingDirectory).GetFiles();

            if (emails.Any())
            {

                if (Settings.ParserMaxBatchSize > 0 && emails.Count() > Settings.ParserMaxBatchSize)
                {
                    emails = emails.Take(Settings.ParserMaxBatchSize).ToArray();
                }

                foreach (var eml in emails)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    var yahooHeatData = new YahooHeatData() {IsFirst = true, ServerId = Settings.ServerID};
                    var archiveFolder = Path.Combine(Settings.ArchiveDirectory, DateTime.Now.ToString("yyyyMMdd"));

                    if (!Directory.Exists(archiveFolder))
                    {
                        log.Info("Creating archive folder: " + archiveFolder);
                        Directory.CreateDirectory(archiveFolder);
                    }

                    try
                    {
                        log.Info("Parsing email " + eml.FullName);

                        var emailMessage = new MailBuilder().CreateFromEmlFile(eml.FullName);

                        yahooHeatData.RawText = emailMessage.RenderEml(true);

                        yahooHeatData.HeatTime = DateTime.Parse(emailMessage.Document.Root.Headers["x-heat-time"]);
                        yahooHeatData.heat_ip = emailMessage.Document.Root.Headers["x-heat-ip"];

                        const string fromRegex = @"\""?(?<fromname>.+)""?\s+<(?<email>.+)>";
                        var match = Regex.Match(emailMessage.Document.Root.Headers["from"], fromRegex);
                        var fromAddress = new MailAddress(match.Groups["email"].ToString(),
                            match.Groups["fromname"].ToString());

                        // FROM
                        //TODO: Where do these go?
                        //yahooHeatData.from = emailMessage.Document.Root.Headers["from"].Replace("\"", string.Empty);
                        yahooHeatData.fromnamedisplay = fromAddress.DisplayName.Replace("\"", "");
                        //yahooHeatData.FromAddress = fromAddress.Address;
                        yahooHeatData.fromemailaddress_user = fromAddress.User;
                        yahooHeatData.fromemailaddress_host = fromAddress.Host;

                        // TO
                        yahooHeatData.toemailaddress = emailMessage.Document.Root.Headers["to"];

                        var recipient = new MailAddress(emailMessage.Document.Root.Headers["to"]);
                        string recipientDomain = recipient.Host;

                        // BULK/INBOX
                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com" ||
                            recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            yahooHeatData.foldername =
                                string.IsNullOrEmpty(emailMessage.Document.Root.Headers["x-yahoofilteredbulk"])
                                    ? "INBOX"
                                    : "BULK";
                        }
                        else if (recipientDomain == "aol.com")
                        {
                            yahooHeatData.foldername = emailMessage.Document.Root.Headers["x-heat-folder"].ToLower() ==
                                                       "inbox"
                                ? "INBOX"
                                : "BULK";
                        }

                        yahooHeatData.subject = emailMessage.Document.Root.Headers["subject"];

                        // SENT TIME
                        yahooHeatData.DateSent = DateTime.Parse(emailMessage.Document.Root.Headers["date"]);

                        var receivedRegex = string.Empty;

                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com" ||
                            recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            receivedRegex =
                                @"\(EHLO\s(?<ehlodomain>[a-zA-Z0-9\-\.]+)\)\s+\((?<ehloip>(?:[0-9]{1,3}.?){4})\)\s+by\s+(?<receivedmx>[a-zA-Z0-9\.\-]+)\s+with\s+SMTP;\s+(?<receiveddate>.+)";
                        }
                        else if (recipientDomain == "aol.com")
                        {
                            receivedRegex =
                                @"\((?<ehlodomain>[a-zA-Z0-9\-\.]+)\s+\[(?<ehloip>(?:[0-9]{1,3}\.?){4})\]\)\s+by\s+(?<receivedmx>[a-zA-Z0-9\.\-]+)\s.+;\s(?<receiveddate>.+)\s\(";
                        }

                        bool matched = false;

                        foreach (var headerValue in emailMessage.Document.Root.Headers.GetValues("received"))
                        {
                            match = Regex.Match(headerValue, receivedRegex,
                                RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);

                            if (match.Success)
                            {
                                yahooHeatData.ehlodomain = match.Groups["ehlodomain"].ToString(); // ehlo domain
                                yahooHeatData.ehloip = match.Groups["ehloip"].ToString(); // ehlo ip
                                yahooHeatData.receivedmx = match.Groups["receivedmx"].ToString(); // received mx
                                yahooHeatData.DateReceived = DateTime.Parse(match.Groups["receiveddate"].ToString());
                                matched = true;
                                break;
                            }

                        }

                        if (!matched)
                        {
                            throw new Exception("Failed to find EHLO info from \"received\" headers");
                        }

                        // SPF
                        string spfHeader = string.Empty;
                        string spfRegex = string.Empty;

                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com"
                            || recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            spfRegex = @"^(\w+)";
                            spfHeader = "received-spf";
                        }
                        else if (recipientDomain == "aol.com")
                        {
                            spfRegex = @"SPF : (\w+)";
                            spfHeader = "x-aol-spf";
                        }

                        if (!string.IsNullOrWhiteSpace(emailMessage.Document.Root.Headers[spfHeader]))
                        {
                            match = Regex.Match(emailMessage.Document.Root.Headers[spfHeader], spfRegex);
                            yahooHeatData.spfheader = match.Groups[1].ToString();
                        }

                        // DomainKey
                        string domainkeysHeader;
                        string domainkeysRegex;

                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com"
                            || recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            domainkeysHeader = "Authentication-Results";
                            domainkeysRegex = @"domainkeys=(\w+)";

                            match = Regex.Match(emailMessage.Document.Root.Headers[domainkeysHeader], domainkeysRegex);
                            yahooHeatData.domainkeysAuthenticationResults = match.Groups[1].ToString();
                        }

                        // DKIM
                        string dkimHeader = string.Empty;
                        string dkimRegex = string.Empty;

                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com"
                            || recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            dkimHeader = "Authentication-Results";
                            dkimRegex = @"dkim=(\w+)";
                        }
                        else if (recipientDomain == "aol.com")
                        {
                            dkimHeader = "x-aol-scoll-authentication";
                            dkimRegex = @"DKIM\s:\s(\w+)";
                        }

                        if (!string.IsNullOrWhiteSpace(emailMessage.Document.Root.Headers[dkimHeader]))
                        {
                            match = Regex.Match(emailMessage.Document.Root.Headers[dkimHeader], dkimRegex);
                            yahooHeatData.dkimAuthenticationResults = match.Groups[1].ToString();
                        }

                        // Recipient domain
                        yahooHeatData.recipientDomain = recipientDomain;

                        const string unsubscribeHeader = "list-unsubscribe";

                        // Base 26 Info
                        if (!string.IsNullOrWhiteSpace(emailMessage.Document.Root.Headers[unsubscribeHeader]))
                        {
                            // Batch-Subscriber-List Id
                            
                            IDictionary<string, int> base26Values;

                            MailingSystem mailingSystem = DetermineMailingSystemFromListUnsubscribe(emailMessage.Document.Root.Headers[unsubscribeHeader]);

                            switch (mailingSystem)
                            {
                                case MailingSystem.WhiteDelivery:
                                    base26Values = GetWdBase26Info(emailMessage.Document.Root.Headers[unsubscribeHeader]);
                                    yahooHeatData.BatchId = base26Values["batch_id"];
                                    yahooHeatData.SubscriberID = base26Values["subscriber_id"];
                                    yahooHeatData.ListID = base26Values["list_id"];
                                    break;
                                case MailingSystem.Avenlo:
                                    base26Values = GetAvenloBase26Info(emailMessage.Document.Root.Headers[unsubscribeHeader]);
                                    yahooHeatData.AvenloDeploymentId = base26Values["action_id"];
                                    yahooHeatData.AvenloRecipientId = base26Values["redirect_id"];
                                    break;
                            }
                        }

                        const string apperentlyToHeader = "x-apparently-to";

                        if (!string.IsNullOrWhiteSpace(emailMessage.Document.Root.Headers[apperentlyToHeader]))
                        {
                            const string apparentlyToRegex =
                                @"(?<apparentFromEmail>.+)\s+via\s+(?<apparentReceivedIp>.+);\s+(?<apparentReceivedDate>.+)";
                            match = Regex.Match(emailMessage.Document.Root.Headers[apperentlyToHeader],
                                apparentlyToRegex);

                            yahooHeatData.received_ip = match.Groups["apparentReceivedIp"].ToString();
                        }

                        if (!PublishMessage(yahooHeatData))
                        {
                            if (Settings.ParserBatchWaitTime < MinimumWaitSecondsOnQueueConnectionFailure)
                            {
                                System.Threading.Thread.Sleep(MinimumWaitSecondsOnQueueConnectionFailure -
                                                              Settings.ParserProcessingDelay);
                            }
                            return;
                        }

                        // archive file
                        string archiveFile = Path.Combine(archiveFolder, eml.Name);
                        eml.MoveTo(archiveFile);
                        log.Debug("Archived file: " + archiveFile);

                    }
                    catch (Exception ex)
                    {
                        log.Error("Failed to parse: " + eml.FullName);
                        log.Error(ex.ToString());
                        eml.MoveTo(Path.Combine(Settings.ErrorDirectory, eml.Name));
                        continue;
                    }
                    if (Settings.ParserProcessingDelay > 0)
                    {
                        System.Threading.Thread.Sleep(Settings.ParserProcessingDelay);
                    }
                }
            }
            else
            {
                log.Info("No emails to parse");
            }
        }
 private static void ProcessEmailAddresses(MailBuilder builder, IEnumerable<EmailAddress> emailAddresses)
 {
     foreach (var emailAddress in emailAddresses)
     {
         switch (emailAddress.Type)
         {
             case EmailAddressType.To:
             {
                 builder.To.Add(new MailBox(emailAddress.Email, emailAddress.Name));
                 break;
             }
             case EmailAddressType.From:
             {
                 builder.From.Add(new MailBox(emailAddress.Email, emailAddress.Name));
                 break;
             }
             case EmailAddressType.CarbonCopy:
             {
                 builder.Cc.Add(new MailBox(emailAddress.Email, emailAddress.Name));
                 break;
             }
             case EmailAddressType.BlindCarbonCopy:
             {
                 builder.Bcc.Add(new MailBox(emailAddress.Email, emailAddress.Name));
                 break;
             }
         }
     }
 }
Esempio n. 47
0
        private bool getAccessToken(string authCode)
        {
            bool getSuccess = false;
            string  accessToken="";
            if(RefreshKey_saved == "")
            {
            consumer.ClientCredentialApplicator =
                     ClientCredentialApplicator.PostParameter(clientSecret);

            IAuthorizationState grantedAccess1 = consumer.ProcessUserAuthorization(authCode);
            bool result=consumer.RefreshAuthorization(grantedAccess1, TimeSpan.FromHours(10));

            accessToken = grantedAccess1.AccessToken;

            // save key
            iniParser parser = new iniParser();
            String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            parser.IniParser(iniPath);
            string _r=grantedAccess1.AccessToken;   //.RefreshToken;
            parser.AddSetting("Setup", "refreshkey", _r);
            parser.SaveSettings();
            myTabControl.SelectedIndex = 0;
            }
            else {
            // change code immediately
               //  consumer.RefreshAuthorization(grantedAccess1, TimeSpan.FromDays(30));
            //accessToken = grantedAccess1.AccessToken;
                 accessToken=RefreshKey_saved;
                 myTabControl.SelectedIndex = 0;
            }
                try
            {

                GoogleApi api = new GoogleApi(accessToken);

                // string user = "******"; // api.GetEmail();
                // GoogleApi api = new GoogleApi(accessToken);

                XmlDocument contacts = api.GetContacts();

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(contacts.NameTable);
                nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
                nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom");
                emailCount = 0;
                foreach (XmlNode contact in contacts.GetElementsByTagName("entry"))
                {
                    XmlNode title = contact.SelectSingleNode("a:title", nsmgr);
                    XmlNode email = contact.SelectSingleNode("gd:email", nsmgr);

                    Console.WriteLine("{0}: {1}",
                        title.InnerText,
                        email.Attributes["address"].Value);
                    mail_arr.Add(email.Attributes["address"].Value);
                    emailCount++;
                 //   listbox1.Items.Add(title.InnerText + " , " + email.Attributes["address"].Value);
                }
                getSuccess = true;
            }
            catch (Exception err)
            {
               // MessageBox.Show("error: " + err.Message);
                Console.WriteLine("Error: " + err.Message);
                getSuccess = false;
                return getSuccess;
            }
            // everything is good, goto input : autocomplete
            contactData.inc(emailCount);
            int i = 0;
            foreach (string emailAddress in mail_arr)
            {
                contactData.States.SetValue(emailAddress, i);
                i++;
            }
            int where = contactData.States.Length;
            //
            AutoCompleteBox.ItemsSource = contactData.States;
            email_list.Items.Clear();
            label_invalid.Visibility = Visibility.Collapsed;
               // myTabControl.SelectedIndex = 0;
            return getSuccess;

            //------------------------
            try
            {
                // get inbox mail content
               // #region get InBox
                string user = "******"; // api.GetEmail();
                using (Imap imap = new Imap())
                {
                    imap.ConnectSSL("imap.gmail.com");
                    imap.LoginOAUTH2(user, accessToken);

                    imap.SelectInbox();
                    List<long> uids = imap.Search(Flag.Unseen);

                    foreach (long uid in uids)
                    {
                        string eml = imap.GetMessageByUID(uid);
                        IMail email = new MailBuilder().CreateFromEml(eml);

                       // listbox1.Items.Add(email.From);
                    }
                    imap.Close();
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("error: " + err.Message);
            }
        }
Esempio n. 48
0
        static void Main(string[] args)
        {
            StreamWriter write = new StreamWriter(ConfigurationManager.AppSettings.Get("ErrorsPath"));

                using (Imap map = new Imap())
                {
                    map.ConnectSSL("imap.gmail.com");
                    map.Login("*****@*****.**", "algSweng500");

                    //select only the inbox to search and only show unread messages
                    map.SelectInbox();
                    List<long> uids = map.Search(Flag.Unseen);

                    foreach (long uid in uids)
                    {
                        try
                        {
                            string eml = map.GetMessageByUID(uid);
                            IMail mail = new MailBuilder().CreateFromEml(eml);

                            string title = mail.Subject;

                            if (!title.Contains("Please purchase"))
                            {

                                string message = mail.Text;

                                //get the stock symbol
                                string[] Symbolsplit = title.Split(new char[0]);
                                string symbol = Symbolsplit[1].ToString();

                                //get the amount to sell or buy
                                string AmountExtract = Regex.Match(title, @"\d+").Value;
                                int quantity = Int32.Parse(AmountExtract);

                                //convert the message and title to lowercase so the if statement will have no errors
                                message = message.ToLower();
                                title = title.ToLower();

                                PortfolioManager Manage = new PortfolioManager();
                                if (message.Contains("yes") && title.Contains("sell"))
                                {
                                    Manage.sell(symbol, quantity);
                                }
                                else if (message.Contains("yes") && title.Contains("buy"))
                                {
                                    Manage.buy(symbol, quantity);
                                }
                                else
                                {
                                    //adding just incase we find a need for it
                                }
                            }
                            else
                            {
                                map.MarkMessageUnseenByUID(uid);
                                write.WriteLine("Mail DLL ERROR");
                            }
                        }
                        catch (Exception ex)
                        {
                            write.WriteLine("Error Occurred Processing Email");
                            write.WriteLine("Email UID: " + uid);
                            write.WriteLine("Exception: " + ex.ToString());
                        }
                    }
                }
                write.Close();
        }
Esempio n. 49
0
 private void _btnLoad_Click(object sender, System.EventArgs e)
 {
     IMail email = new MailBuilder().CreateFromEml(File.ReadAllText("Order.eml"));
     _mailBrowser.Navigate(new MailHtmlDataProvider(email));
 }
        private async void btnPost_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            ProgBar.IsIndeterminate = true;

            EnableControl(false);

            if (txtBoxContent.Text != "")
            {
                string Content =
                    "From: " + txtBoxFrom.Text
                    + Environment.NewLine //New line
                    + "To: " + txtBoxTo.Text
                    + Environment.NewLine
                    + Environment.NewLine
                    + "Content: "
                    + Environment.NewLine
                    + txtBoxContent.Text
                    + Environment.NewLine
                    + Environment.NewLine
                    + "Sent from Nguyen An Ninh Confession App for Windows Phone :)";

                MailBuilder myMail = new MailBuilder();
                myMail.Text = Content;
                myMail.Subject = 
                    "New Confession from Windows Phone app - From "
                    + txtBoxFrom.Text 
                    + " - To "
                    + txtBoxTo.Text;
                //await myMail.AddAttachment(attachFile);
                myMail.To.Add(new MailBox("*****@*****.**"));
                myMail.From.Add(new MailBox("*****@*****.**"));

                IMail email = myMail.Create();

                try
                {
                    using (Smtp smtp = new Smtp())
                    {
                        await smtp.Connect("smtp.example.com", 25); //Change smtp address and port
                        await smtp.StartTLS();
                        await smtp.UseBestLoginAsync("*****@*****.**", "ExamplePassword"); //Change email credentials information
                        await smtp.SendMessageAsync(email);
                        await smtp.CloseAsync();

                        var msg = new MessageDialog("Your confession has been successfully sent!").ShowAsync();

                        ProgBar.IsIndeterminate = false;
                        EnableControl(true);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString()); //Use this to show Exception in the Output window.
                    var msgDialog = new MessageDialog("Please try again :(", "Failed to post").ShowAsync();
                    ProgBar.IsIndeterminate = false;
                    EnableControl(true);
                }
            }
            else
            {
                var msgDialog = new MessageDialog("Put something in before sending.", "Nothing to send").ShowAsync();
                EnableControl(true);
            }
        }
Esempio n. 51
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        SMS.APIType = SMSGateway.Site2SMS;
        SMS.MashapeKey = "pPsD7Kqfn2mshzjqhhbOkQMfGyQgp1TQAf7jsnRTMs6ygiLeUg";
        string text = "";
        //Email starts
        using (Imap imap = new Imap())
        {
            Limilabs.Mail.Log.Enabled = true;
            try
            {
                imap.ConnectSSL("imap.gmail.com", 993);   // or ConnectSSL for SSL

                imap.UseBestLogin("*****@*****.**", "zeesense40");
            }
            catch(Exception E)
            {
                return;
            }

            imap.SelectInbox();

            List<long> uids = imap.Search(Flag.All);



            foreach (long uid in uids)
            {

                var eml = imap.GetMessageByUID(uid);

                IMail email = new MailBuilder()

                    .CreateFromEml(eml);


                 text = email.Text;

                 
            
             
           }

            imap.Close();
        }
           
        //Email ends
            string[] arr=text.Split('~');
            string recvName = "",alert="";
        if(arr[0]=="&")
        {
            recvName = arr[2].ToLower().Trim();
            alert = arr[3];
        }
        else if(arr[0]=="^" || arr[0]=="%")
        {
            recvName = arr[2].ToLower().Trim();
            alert = arr[1];
        }
        //txtyourmoNumber.Text = "9742984490";
        SMS.Username = "******";
        //txtyourPassword.Text = "12345";
        SMS.Password = "******";
        //string recvName = arr[2].ToLower().Trim();
      //  string alert = arr[3];
        string phone = null;
        string tableName = "builder";
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
                CloudTableClient tableClient1 = storageAccount.CreateCloudTableClient();
                CloudTable table1 = null;
                try
                {
                    table1 = tableClient1.GetTableReference(tableName);
                    TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("customername", QueryComparisons.Equal, recvName.ToLower()));
                    List<CustomerEntity> AddressList = new List<CustomerEntity>();
                    CustomerEntity ce = new CustomerEntity();
                    foreach (CustomerEntity entity in table1.ExecuteQuery(query))
                    {
                        phone = entity.contactnumber;
                        break;
                    }
                    if (phone != null)
                    
                        SMS.SendSms(phone, alert);
                        //SendingRandomMessages(recvName, data).Wait();
                    
                }
               catch(Exception e1)
                {
                 
                }
    }
Esempio n. 52
-9
        static void Main()
        {
            using (Imap imap = new Imap())
            {
                imap.Connect(_server);              // Use overloads or ConnectSSL if you need to specify different port or SSL.
                imap.Login(_user, _password);       // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                    // or use UseBestLogin method if you want Mail.dll to choose for you.
                imap.SelectInbox();
                                                    // All search methods return list of unique ids of found messages.

                List<long> unseen = imap.SearchFlag(Flag.Unseen);           // Simple 'by flag' search.

                List<long> unseenReports = imap.Search(new SimpleImapQuery  // Simple 'by query object' search.
                {
                    Subject = "report",
                    Unseen = true,
                });

                List<long> unseenReportsNotFromAccounting = imap.Search(    // Most advanced search using ExpressionAPI.
                    Expression.And(
                        Expression.Subject("Report"),
                        Expression.HasFlag(Flag.Unseen),
                        Expression.Not(
                            Expression.From("*****@*****.**"))
                ));

                foreach (long uid in unseenReportsNotFromAccounting)        // Download emails from the last result.
                {
                    IMail email = new MailBuilder().CreateFromEml(
                        imap.GetMessageByUID(uid));
                    Console.WriteLine(email.Subject);
                }

                imap.Close();
            }
        }