Ejemplo n.º 1
11
        public async Task<ActionResult> Index(CancellationToken cancellationToken, GmailFormModel email)
        {
            //return View();

            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                AuthorizeAsync(cancellationToken);

            AuthorizationCodeMvcApp o = new AuthorizationCodeMvcApp(this, new AppFlowMetadata());


            if (result.Credential != null)
            {
                if (email.to != null)
                {
                    BaseClientService.Initializer initializer = new BaseClientService.Initializer
                    {
                        HttpClientInitializer = result.Credential,
                        ApplicationName = "ASP.NET MVC Sample5"
                    };

                    var service = new GmailService(initializer);

                    string fromEmail = "*****@*****.**";
                    //string fromName = @"AdamMorgan";
                    string fromName = "";

                    /// This code ss needed to extract signed in user info (email, display name)
                    var gps = new PlusService(initializer);
                    var me = gps.People.Get("me").Execute();
                    fromEmail = me.Emails.First().Value;
                    //fromName = me.DisplayName;
                    ////////////////////////////////////////

                    MimeMessage message = new MimeMessage();
                    message.To.Add(new MailboxAddress("", email.to));
                    if (email.cc != null)
                        message.Cc.Add(new MailboxAddress("", email.cc));
                    if (email.bcc != null)
                        message.Bcc.Add(new MailboxAddress("", email.bcc));
                    if (email.subject != null)
                        message.Subject = email.subject;

                    var addr = new MailboxAddress(fromName, fromEmail);
                    message.From.Add(addr);
                    if (email.body != null)
                    {
                        message.Body = new TextPart("html")
                        {
                            Text = email.body
                        };
                    }

                    var ms = new MemoryStream();
                    message.WriteTo(ms);
                    ms.Position = 0;
                    StreamReader sr = new StreamReader(ms);
                    Google.Apis.Gmail.v1.Data.Message msg = new Google.Apis.Gmail.v1.Data.Message();
                    string rawString = sr.ReadToEnd();

                    byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
                    msg.Raw = System.Convert.ToBase64String(raw);
                    var res = service.Users.Messages.Send(msg, "me").Execute();

                }
                return View();
            }
            else
            {
                string redirectUri = result.RedirectUri;
                
                /// Remove port from the redirect URL.
                /// This action is needed for http://gmailappasp.apphb.com/ application only.
                /// Remove it if you hosted solution not on the http://gmailappasp.apphb.com/
                redirectUri = Regex.Replace(result.RedirectUri, @"(:\d{3,5})", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                ///

                return new RedirectResult(redirectUri);
            }
        }
 public void DisplayMessage(string _messageId, Message message)
 {
     var byteArr = Attachment.CreateAttachmentFromString("", message.Payload.Parts[0].Body.Data);
     var converted = Convert.FromBase64String(byteArr.Name.Replace('-', '+').Replace('_', '/'));
     messageDisplay.Text = System.Text.Encoding.ASCII.GetString(converted);
 }
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials_dev.json", FileMode.Open,
                                      FileAccess.Read))
            {
                string credPath = "token_Send.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }
            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            // Define parameters of request.
            string plainText = "To:[email protected]\r\n" +
                               "Subject: Gmail Send API Test\r\n" +
                               "Content-Type: text/html; charset=us-ascii\r\n\r\n" +
                               "<h1>TestGmail API Testing for sending <h1>";
            var newMsg = new Google.Apis.Gmail.v1.Data.Message();

            newMsg.Raw = SendMail.Base64UrlEncode(plainText.ToString());
            service.Users.Messages.Send(newMsg, "me").Execute();
            Console.Read();
        }
Ejemplo n.º 4
0
        public static bool SendMail(string contacto, string pathTemplate)
        {
            try
            {
                UserCredential credential = GetCredential();
                GmailService   service    = GetService(credential);

                //string plainText = $"To: {contacto}\r\n" +
                //               $"Subject: {ProcesoPrincipal.Instancia.ProcesoMensaje.Asunto} Test\r\n" +
                //               "Content-Type: text/html; charset=us-ascii\r\n\r\n" +
                //               $"<h1>{ProcesoPrincipal.Instancia.ProcesoMensaje.CuerpoMensaje}</h1>" +
                //               $"{ConvertDocToHtml(Path.Combine(Directory.GetCurrentDirectory(), @"Templates\Template.docx"), Path.Combine(Directory.GetCurrentDirectory(), @"Templates\Template.html"))}";
                string plainText = $"To: {contacto}\r\n" + "Subject: Test\r\n" + ObtenerTemplate(pathTemplate);

                var newMsg = new Google.Apis.Gmail.v1.Data.Message();
                newMsg.Raw = Base64UrlEncode(plainText.ToString());
                //service.Users.Messages.Send(newMsg, "me").Execute();
                return(true);
            }
            catch (Exception)
            {
                //TODO: Acá loggear en ruta especifica de log el motivo real
                return(false);
            }
        }
Ejemplo n.º 5
0
        // *********************************************** //
        //  This is the section for dealing with user      //
        //    emails, these methods send, receive, and     //
        //    format emails to be sent to sales reps/users //
        //                                                 //
        // *********************************************** //
        #region Sending Email methods...

        // sends the email from passed variables.
        private void send(string repName, string repEmail, string messageId)
        { // creating a mailClient to send to customers
            SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

            mailClient.EnableSsl             = true;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials           = new NetworkCredential("{[email protected]}", "{yourEmailPassword}");
            MailAddress to = new MailAddress(repEmail, repName);

            System.Net.Mail.MailMessage msgMail = new System.Net.Mail.MailMessage();
            msgMail.From = new MailAddress("{[email protected]}", "{name}");
            List <MailAddress> cc = new List <MailAddress>();

            Google.Apis.Gmail.v1.Data.Message message = googleAPI.GetMessage(messageId);
            msgMail.To.Add(to);

            foreach (MailAddress addr in cc)
            {
                msgMail.CC.Add(addr);
            }

            msgMail.Subject    = "{subjectLine}";
            msgMail.Body       = googleAPI.GetEmailBody(message);
            msgMail.IsBodyHtml = true;
            mailClient.Send(msgMail);
            msgMail.Dispose();
            mailClient.Dispose();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Prepares MailMessage object for Gmail API
        /// </summary>
        /// <param name="to">To field of a message</param>
        /// <param name="from">From field of a message</param>
        /// <param name="subject">Subject field of a message</param>
        /// <param name="bodyHtml">HTML formatted body of a message</param>
        /// <returns>Result message</returns>
        private static Google.Apis.Gmail.v1.Data.Message CreateGmailMessage(string from, string to, string subject, string bodyHtml)
        {
            MailMessage mailMessage = new MailMessage();

            mailMessage.From = new MailAddress(from);
            string[] splittedTo = to.Split(new Char[] { ';', ',' });
            foreach (string t in splittedTo)
            {
                mailMessage.To.Add(t.Trim());
            }

            mailMessage.ReplyToList.Add(from);
            mailMessage.Subject    = subject;
            mailMessage.Body       = bodyHtml;
            mailMessage.IsBodyHtml = true;

            MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

            Google.Apis.Gmail.v1.Data.Message gmailMessage = new Google.Apis.Gmail.v1.Data.Message
            {
                Raw = Base64UrlEncoder.Encode(mimeMessage.ToString())
            };

            return(gmailMessage);
        }
Ejemplo n.º 7
0
        public void sendMessage()
        {
            txtMessage = File.ReadAllText(@"F:/ecoTilly/sample.htm");
            UserCredential credential;

            //read credentials file
            using (FileStream stream = new FileStream(@"F:\Technology\EcoTill\credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                credPath   = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes,
                                                                         "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
            }

            string plainText = "To: " + to + "\r\n" +
                               "Subject: " + txtSubject + "\r\n" +
                               "Content-Type: text/html; charset=utf-8\r\n\r\n" +
                               "<h1>" + txtMessage + "</h1>";

            //call gmail service
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            var newMsg = new Google.Apis.Gmail.v1.Data.Message();

            newMsg.Raw = Base64UrlEncode(plainText.ToString());
            service.Users.Messages.Send(newMsg, "me").Execute();
            Console.WriteLine("Your email has been successfully sent !");
        }
Ejemplo n.º 8
0
        public void SendEmail(GmailService service, string userId, Email email)
        {
            var mailMessage = new System.Net.Mail.MailMessage();

            mailMessage.From = new System.Net.Mail.MailAddress(email.From);
            mailMessage.To.Add(email.To);
            mailMessage.ReplyToList.Add(email.From);
            mailMessage.Subject    = email.Subject;
            mailMessage.Body       = email.Message;
            mailMessage.IsBodyHtml = true;

            foreach (var ccn in email.Ccn)
            {
                mailMessage.Bcc.Add(ccn);
            }

            //foreach (System.Net.Mail.Attachment attachment in email.Attachments)
            //{
            //    mailMessage.Attachments.Add(attachment);
            //}

            var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

            var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
            {
                Raw = Encode(mimeMessage.ToString())
            };

            Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, userId);

            request.Execute();
        }
Ejemplo n.º 9
0
        private async void btnSendCompose_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UserCredential credential = await serviceGmail.getCredential();

                if (credential != null)
                {
                    var service = new GmailService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = "Gmail API",
                    });
                    string plainText = string.Format("To: {0}\r\n" +
                                                     "Subject: {1}\r\n" +
                                                     "Content-Type: text/html; charset=us-ascii\r\n\r\n" +
                                                     "<h1>{2}</h1>", txtEmailSend.Text, txtSubject.Text, txtContentSend.Text);

                    var newMsg = new Google.Apis.Gmail.v1.Data.Message();
                    newMsg.Raw = Base64UrlEncode(plainText.ToString());
                    service.Users.Messages.Send(newMsg, "me").Execute();
                    ShowHideCompose.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception) { }
        }
Ejemplo n.º 10
0
        public static GmailMessage GetFakeGmailMessage(
            string from    = "*****@*****.**",
            string to      = "*****@*****.**",
            string subject = "test subject",
            string content = "test content")
        {
            var mess = new MailMessage
            {
                Subject = subject,
                From    = new MailAddress(from)
            };

            mess.To.Add(new MailAddress(to));

            var adds = AlternateView.CreateAlternateViewFromString(content, new System.Net.Mime.ContentType("text/plain"));

            adds.ContentType.CharSet = Encoding.UTF8.WebName;
            mess.AlternateViews.Add(adds);

            var mime         = MimeMessage.CreateFromMailMessage(mess);
            var gmailMessage = new GmailMessage()
            {
                Raw      = GMailService.Base64UrlEncode(mime.ToString()),
                ThreadId = "1"
            };

            return(gmailMessage);
        }
Ejemplo n.º 11
0
        public static void SendEmail(YanapayEmail email, GmailService service)
        {
            var mailMessage = new System.Net.Mail.MailMessage();

            mailMessage.From = new System.Net.Mail.MailAddress(email.FromAddress);
            mailMessage.To.Add(email.ToRecipients);
            mailMessage.ReplyToList.Add(email.FromAddress);
            mailMessage.Subject         = email.Subject;
            mailMessage.Body            = email.Body;
            mailMessage.IsBodyHtml      = email.IsHtml;
            mailMessage.BodyEncoding    = System.Text.Encoding.GetEncoding("ISO-8859-1");
            mailMessage.HeadersEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
            mailMessage.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");

            var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

            var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
            {
                Raw = Encode(mimeMessage.ToString())
            };

            Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, "me");

            request.Execute();
        }
Ejemplo n.º 12
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();
        }
Ejemplo n.º 13
0
        public void SendEmail(IGenericEmail email)
        {
            var message = new Google.Apis.Gmail.v1.Data.Message();

            message.Raw = ConvertBase64UrlEncode(email.GetEmail());
            gmailService.Users.Messages.Send(message, "me").Execute();
        }
        private void NewMethod(String receiverName, string receiverAddress, string subject, string body)
        {
            try
            {
                UserCredential credential;

                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { GmailService.Scope.GmailReadonly, GmailService.Scope.MailGoogleCom, GmailService.Scope.GmailModify },
                        "user",
                        CancellationToken.None,
                        new FileDataStore(this.GetType().ToString())).Result;


                    var service = new GmailService(new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = "Gmail API",
                    });

                    var text = string.Format("From: {0} <{1}>\nTo: {2} <{3}>\nSubject: {4}\nDate: Thu, 29 Mar 2018 22:19:06 -0600\nMessage-ID: <*****@*****.**>\n\n{5}",
                                             "Computational Physiology Labs",
                                             "*****@*****.**",
                                             receiverName,
                                             receiverAddress,
                                             subject,
                                             body);

                    Console.WriteLine("Send email:\n{0}", text);

                    var encodedText = System.Text.Encoding.UTF8.GetBytes(text);
                    //var encodedText = System.Web.HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(text));

                    var convertedText = Convert.ToBase64String(encodedText).Replace('+', '-').Replace('/', '_').Replace("=", "");

                    Console.WriteLine("Raw email:\n{0}", encodedText);

                    var message = new Google.Apis.Gmail.v1.Data.Message {
                        Raw = convertedText
                    };



                    var request = service.Users.Messages.Send(message, "me").Execute();

                    Console.WriteLine(
                        string.IsNullOrEmpty(request.Id) ? "Issue sending, returned id: {0}" : "Email looks good, id populated: {0}",
                        request.Id);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception encountered: {0}", e.Message);
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            GmailApplicationService GmailApplicationService = new GmailApplicationService();

            //string outputPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Teste");
            string outputPath = ConfigurationManager.AppSettings["outputPath_files"].ToString();

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            #region [ Testes de Mensagens ]
            var ListMessages = GmailApplicationService.ListAllMessages(false, new List <string> {
                "CATEGORY_PERSONAL"
            }, 100);

            foreach (var messageId in ListMessages)
            {
                // carrega a mensagem
                Google.Apis.Gmail.v1.Data.Message message = GmailApplicationService.GetMessage(messageId.Id);

                // baixa as imagens
                //GmailApplicationService.GetImagesAttachments(message, outputPath);
            }



            #endregion

            #region [ Teste de Labels ]
            //var Labels = GmailApplicationService.GetLabels();

            //foreach (var item in Labels.Where(c => c.Type == "system").OrderBy(c => c.Type == "system").ThenBy(c => c.Name))
            //{
            //    Console.WriteLine($"► {item.Name} - [ID_LABEL]: {item.Id}");

            //    if (item.Id == "CATEGORY_PERSONAL")
            //    {
            //        var label = GmailApplicationService.GetLabel(item.Id);

            //        string json = Newtonsoft.Json.JsonConvert.SerializeObject(label, Newtonsoft.Json.Formatting.Indented);

            //        Console.WriteLine(json);
            //    }
            //}
            #endregion

            #region [ Teste de Profile ]
            //var profile = GmailApplicationService.GetUserProfile();
            #endregion



            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Ejemplo n.º 16
0
        // This will take the html body of an email with order details
        //     and parse information into a list that can be used in a
        //     quick manner.
        public List <string> ConvertToLineItems(Google.Apis.Gmail.v1.Data.Message message, GoogleAPI googleAPI)
        {
            string body = FormatBody(googleAPI.GetEmailBody(message));

            string[]      words       = RemoveBrackets(body);
            List <string> productList = RemoveSkus(words);

            productList = FormatProductList(productList);

            return(productList);
        }
        public List <Message> GetFullMessages(GmailService service, string userName, List <Message> allMessages)
        {
            var newMessages = new List <Message>();

            foreach (var message1 in allMessages)
            {
                Message message2 = _emailLoadManager.GetMessage(service, userName, message1.Id);
                newMessages.Add(message2);
                dropdownLoadProgressBar.Increment(1);
            }
            return(newMessages);
        }
Ejemplo n.º 18
0
        public static MimeMessage ToMimeMessage(this Google.Apis.Gmail.v1.Data.Message message)
        {
            if (message.Raw == null)
            {
                throw new ArgumentException("Gmail message is missing raw body. You need to fetch it with raw format");
            }
            var         raw = message.Raw.Base64UrlDecode();
            MimeMessage result;

            using (var stream = new MemoryStream(raw))
            {
                result = MimeMessage.Load(stream);
            }
            return(result);
        }
Ejemplo n.º 19
0
        private void lblEsqueci_Click(object sender, EventArgs e)
        {
            using (capdeEntities context = new capdeEntities())
            {
                if (!String.IsNullOrEmpty(textBox1.Text))
                {
                    Usuario user = context.Usuarios.Where(x => x.Login == textBox1.Text).FirstOrDefault();

                    if (user != null)
                    {
                        string newPass = RandonNumer();

                        user.Senha = crypt.newHash(user.Login + newPass);
                        common.SaveChanges_Database(context, true);

                        UserCredential credential = gmail.Autenticate();
                        using (GmailService service = gmail.AbrirServico(credential))
                        {
                            string plainText = "To: " + user.Email + "\r\n" +
                                               "Subject: CAPDE - Nova senha\r\n" +
                                               "Content-Type: text/html; charset=us-ascii\r\n\r\n" +
                                               "<h2>CAPDE</h2>\r\n\r\n" +
                                               "<p>Olá " + user.Nome + ", você solicitou a troca da sua senha.</p>" +
                                               "</p><b>Nova senha: </b>" + newPass + "</p>";

                            Google.Apis.Gmail.v1.Data.Message message = new Google.Apis.Gmail.v1.Data.Message
                            {
                                Raw = Base64UrlEncode(plainText),
                            };

                            gmail.SendMessage(service, "me", message);
                        }

                        MessageBox.Show("Sua senha foi redefinida e encaminhada uma nova para " + user.Email, "Redefinir Senha",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Usuário inexistente", "Usuário inexistente", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("O valor para 'Usuário' deve ser definido", "Usuário inexistente", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
            }
        }
Ejemplo n.º 20
0
        public void sendMail(string mailClient, string nomFichier)
        {
            //Chemin d'accès
            DirectoryInfo dirBeforeAppli = Directory.GetParent(Convert.ToString(Directory.GetParent(Convert.ToString(Directory.GetParent(Convert.ToString(Directory.GetParent(Directory.GetCurrentDirectory())))))));

            //Create Message
            MailMessage mail = new MailMessage();

            mail.Subject    = "Devis Île de Loisirs de Vaires-Torcy";
            mail.Body       = "Bonjour, \r\n\r\nVeuillez trouver ci joint votre devis pour la baignade. \r\n\r\nBonne journee, Cordialement. \nDJEMMAA Walid\r\n\r\n\r\n--\r\nAccueil Plage\r\[email protected]\r\nPole baignade\r\nRoute de Lagny\r\n77200 Torcy\r\nTel: 0160200204 (touche 2)\r\nFax: 0164809149";
            mail.From       = new MailAddress("*****@*****.**");
            mail.IsBodyHtml = false;
            string joint = dirBeforeAppli + @"\Devis" + DateTime.Today.Year.ToString() + @"\5860" + (DateTime.Today.Year - 2000) + "-" + nomFichier + ".xlsx";

            mail.Attachments.Add(new Attachment(joint));
            mail.To.Add(new MailAddress(mailClient));
            MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);

            Google.Apis.Gmail.v1.Data.Message message = new Message();
            message.Raw = Base64UrlEncode(mimeMessage.ToString());

            //Gmail API credentials
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scope,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            //Send Email
            var result = service.Users.Messages.Send(message, "me").Execute();
        }
Ejemplo n.º 21
0
        public async Task <bool> SendEmailAsync(string destinationMail, string subject, string msg)
        {
            if (!InternetAddress.TryParse(destinationMail, out InternetAddress to))
            {
                return(false);
            }
            if (!InternetAddress.TryParse(Settings.EmailAddress, out InternetAddress from))
            {
                return(false);
            }

            try
            {
                MimeMessage message = new MimeMessage();
                message.Subject = subject;
                message.From.Add(from);
                message.To.Add(to);
                message.Body = new TextPart(TextFormat.Html)
                {
                    Text = msg
                };
                message.ReplyTo.Add(from);

                var gmailService = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = await GetCredentials(),
                    ApplicationName       = "chop9ja"
                });

                string raw          = Encode(message.ToString());
                var    gmailMessage = new GMailMessage {
                    Raw = raw
                };

                var request = gmailService.Users.Messages.Send(gmailMessage, Settings.EmailAddress);

                await request.ExecuteAsync();

                return(true);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "An error occured while attempting to send a mail.");
            }

            return(false);
        }
Ejemplo n.º 22
0
        public void SendEmail(string senderAddress, string address, string body, string attachmentPath)
        {
            credential = GetCredentials();
            var service = GetService(credential);

            System.Net.Mail.MailMessage message = CreateMimeMessage(senderAddress, address, body);
            var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
            {
                Raw = Base64UrlEncode(message.ToString())
            };

            Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, senderAddress);

            var result = request.Execute();

            MessageBox.Show($"Mail sent - {result.Id}");
        }
Ejemplo n.º 23
0
 ///<summary>Throws exceptions if failing to send emails or authenticate with Google.</summary>
 private static void SendEmailOAuth(BasicEmailAddress address, BasicEmailMessage message)
 {
     using GmailApi.GmailService gService = GoogleApiConnector.CreateGmailService(address);
     try {
         GmailApi.Data.Message gmailMessage = CreateGmailMsg(address, message);
         gService.Users.Messages.Send(gmailMessage, address.EmailUsername).Execute();
     }
     catch (GoogleApiException gae) {
         gae.DoNothing();
         //This will bubble up to the UI level and be caught in a copypaste box.
         throw new Exception("Unable to authenticate with Google: " + gae.Message);
     }
     catch (Exception ex) {
         //This will bubble up to the UI level and be caught in a copypaste box.
         throw new Exception($"Error sending email with OAuth authorization: {ex.Message}");
     }
 }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
0
        public string SendGoogleMail(GoogleMail googleMail)
        {
            string result = "FAILED";

            try
            {
                string credentialsPath    = ConfigurationManager.AppSettings["GSuiteCredntial"];
                string credentialsPathNew = ConfigurationManager.AppSettings["GSuiteCredentialNew"];

                UserCredential credential;
                //read credentials file
                using (FileStream stream = new FileStream(credentialsPath, FileMode.Open, FileAccess.Read))
                {
                    string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    credPath   = credentialsPathNew;
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
                }

                string plainText = $"To: " + googleMail.ToMail + "  \r\n" +
                                   $"Subject: " + googleMail.Subject + " \r\n" +
                                   "Content-Type: text/html; charset=utf-8\r\n\r\n" +
                                   $"<h1>" + googleMail.Body + "</h1>";

                //call gmail service
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                var newMsg = new Google.Apis.Gmail.v1.Data.Message();
                newMsg.Raw = Base64UrlEncode(plainText.ToString());
                service.Users.Messages.Send(newMsg, "me").Execute();
                result = "SUCCESS";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Ejemplo n.º 26
0
        public async Task SendMail(string email, string subject, string message)
        {
            UserCredential credential;

            //urs: https://developers.google.com/gmail/api/quickstart/dotnet
            //Habilite o Gmail API, baixe o arquivo json de autenticação e salve na pasta de inicialização
            using (var stream =
                       new FileStream("Send.json", FileMode.Open,
                                      FileAccess.Read))
            {
                string credPath = "Auth-jason.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    System.Threading.CancellationToken.None,
                    new Google.Apis.Util.Store.FileDataStore(credPath, true)).Result;
            }

            // Criar API do serviço de gmail
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parâmetros para o corpo do email
            string plainText = string.Format("To:{0}\r\n", email) +
                               string.Format("Subject: {0}\r\n", subject) +
                               string.Format("Content-Type: text/html; charset=utf-8\r\n\r\n") +
                               string.Format("<h2>{0}<h1>", message);

            var newMsg = new Google.Apis.Gmail.v1.Data.Message();

            newMsg.Raw = Encode(plainText.ToString());
            service.Users.Messages.Send(newMsg, "me").Execute();

            await Task.CompletedTask;
        }
Ejemplo n.º 27
0
        public void DoSendMail(Mail mail)
        {
            try
            {
                // Create Gmail API service.
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                var newMsg = new Google.Apis.Gmail.v1.Data.Message
                {
                    Raw = Base64UrlEncode(mail.FormatedMail)
                };

                var result = service.Users.Messages.Send(newMsg, "me").Execute();
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 28
0
        private void sendMailAsync(System.Net.Mail.MailMessage mailMessage)
        {
            var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

            var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
            {
                Raw = Encode(mimeMessage.ToString())
            };


            UserCredential credential;

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, "me");

            request.Execute();
        }
Ejemplo n.º 29
0
        public static async Task <List <string[]> > GetEmailsAndScrapeThem(string search,
                                                                           Action <string[]> onAdd)
        {
            var rows = new List <string[]>();

            UsersResource.MessagesResource.ListRequest request =
                GmailService.Users.Messages.List("me");
            request.MaxResults = int.MaxValue;
            request.Q          = search;
            IList <Message> messages = (await request.ExecuteAsync()).Messages;

            if (messages == null || messages.Count <= 0)
            {
                return(rows);
            }
            try
            {
                foreach (Message message in messages)
                {
                    if (Stop)
                    {
                        break;
                    }

                    UsersResource.MessagesResource.GetRequest req =
                        GmailService.Users.Messages.Get("me", message.Id);
                    Message mes = await req.ExecuteAsync();

                    string a;
                    if (!string.IsNullOrEmpty(mes.Payload.Parts[0].Body.Data))
                    {
                        a = mes.Payload.Parts[0].Body.Data;
                    }
                    else if (mes.Payload.Parts[0].Parts[0].Parts != null)
                    {
                        a = mes.Payload.Parts[0].Parts[0].Parts[1].Body.Data;
                    }
                    else
                    {
                        a = mes.Payload.Parts[0].Parts[1].Body.Data;
                    }

                    if (a == null)
                    {
                        continue;
                    }
                    string body    = Utf8.GetString(WebEncoders.Base64UrlDecode(a));
                    var    results = new string[FieldsList.Count];
                    for (var i = 0; i < FieldsList.Count; i++)
                    {
                        FieldToFind f       = FieldsList[i];
                        Match       rcMatch = Regex.Match(body, f.Regex, RegExOptions);
                        if (f.Required && !rcMatch.Success)
                        {
                            results[i] = "NOT FOUND";
                        }
                        else
                        {
                            results[i] = rcMatch.Groups[f.GroupNumber].Value;
                        }
                    }

                    onAdd(results);
                    rows.Add(results);
                }
            }
            catch
            {
                // ignored
            }

            return(rows);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Sends a message using Gmail API
        /// </summary>
        /// <param name="msg">Message to send</param>
        /// <returns>JSON serialized string of a result object</returns>
        public string Send(EmailMessage msg)
        {
            string emailTemplate = GetMsgTemplate(msg.template.templateId);

            if (null == emailTemplate)
            {
                _logger.LogError($"Unable to load Email template with id {msg.template.templateId}");
                return(null);
            }

            string htmlBody = null;
            string subject  = null;

            ServiceCollection services = new ServiceCollection();

            services.AddNodeServices();

            using (ServiceProvider serviceProvider = services.BuildServiceProvider())
            {
                NodeServicesOptions options = new NodeServicesOptions(serviceProvider) /* Assign/override any other options here */ }
                {
                    ;
                    using (INodeServices nodeServices = NodeServicesFactory.CreateNodeServices(options))
                    {
                        htmlBody = nodeServices.InvokeAsync <string>("pugcompile", emailTemplate, null == msg.bodyModel ? null: JsonConvert.DeserializeObject(msg.bodyModel)).Result;
                        subject  = nodeServices.InvokeAsync <string>("pugcompile", msg.template.subjectTemplate, null == msg.subjectModel ? null : JsonConvert.DeserializeObject(msg.subjectModel)).Result;
                    }
            }

            services.Clear();

            if (null == subject)
            {
                _logger.LogError($"Unable to load email subject");
                return(null);
            }

            if (null == emailTemplate)
            {
                _logger.LogError($"Unable to load Email template with id {msg.template.templateId}");
                return(null);
            }

            UserCredential credential;

            string[] scopes = { GmailService.Scope.GmailSend };

            using (FileStream stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;

                _logger.LogInformation("Google credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            using (GmailService service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "MailGmail",
            }))
            {
                Google.Apis.Gmail.v1.Data.Message message       = CreateGmailMessage(msg.from, msg.to, subject, htmlBody);
                Google.Apis.Gmail.v1.Data.Message messageResult = service.Users.Messages.Send(message, "me").Execute();

                return(JsonConvert.SerializeObject(messageResult));
            }
        }
        // This method using the Google API to send emails
        public static void sendEmailLessThanZero(string emailErrorResult)
        {
            Console.WriteLine("Trying to send an Email because error with {0} has occurred", emailErrorResult);

            // Declaring the email addresses used in this method, have not entered the correct emails addresses as for security reason
            // In a live version of this method the email addresses will be held in a more secure model
            string         youremailName      = "EnterName";
            string         youremailAddress   = "*****@*****.**";
            string         sendToName         = "EnterNameSendingto";
            string         sendToEmailAddress = "*****@*****.**";
            UserCredential credential;

            // A JSON secret file needs to be be generated in the Google API Manager to allow for authentication
            string locationGoogleClientSecretFile = "Enter location of the JSON Google API client secret file";

            using (var stream = new FileStream(locationGoogleClientSecretFile, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                credPath   = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, new[] {
                    GmailService.Scope.MailGoogleCom,
                    GmailService.Scope.GmailCompose,
                    GmailService.Scope.GmailModify, GmailService.Scope.GmailSend
                },
                                                                         "user",
                                                                         CancellationToken.None,
                                                                         new FileDataStore(credPath, true)).Result;

                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "GmailService API .NET Quickstart",
                });

                // The below code builds the message body of the mail, builder.HtmlBody can be used to build a HTML email if needed
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(youremailName, youremailAddress));
                message.To.Add(new MailboxAddress(sendToName, sendToEmailAddress));

                message.Subject = "An error has occurred with the calculations";
                var      builder  = new BodyBuilder();
                DateTime dateTime = DateTime.Now;
                string   strDate  = dateTime.ToString("HH:MM:ss, dddd, MMMM d, yyyy");

                builder.TextBody = @"An error has occurred with " + emailErrorResult + " at the followinf date time " + strDate;
                var contentId = MimeUtils.GenerateMessageId();

                // The email needs to be encoded before sending via the Google API
                message.Body = builder.ToMessageBody();
                var rawMessage = "";
                using (var streem = new MemoryStream())
                {
                    message.WriteTo(streem);
                    rawMessage = Convert.ToBase64String(streem.GetBuffer(), 0,
                                                        (int)streem.Length)
                                 .Replace('+', '-')
                                 .Replace('/', '_')
                                 .Replace("=", "");
                }

                var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
                {
                    Raw = rawMessage
                };

                // Send the encoded email and wrap in a Try Catch encase the email send is not successfully sent and report an erro has occured
                try
                {
                    service.Users.Messages.Send(gmailMessage, sendToEmailAddress).Execute();
                }
                catch (Exception e)
                {
                    Console.WriteLine("There was a problem sending the email via the Google Api");
                }
            }
        }
Ejemplo n.º 32
0
        public async Task <ActionResult> Index(CancellationToken cancellationToken, GmailFormModel email)
        {
            //return View();

            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                         AuthorizeAsync(cancellationToken);

            AuthorizationCodeMvcApp o = new AuthorizationCodeMvcApp(this, new AppFlowMetadata());


            if (result.Credential != null)
            {
                if (email.to != null)
                {
                    BaseClientService.Initializer initializer = new BaseClientService.Initializer
                    {
                        HttpClientInitializer = result.Credential,
                        ApplicationName       = "ASP.NET MVC Sample5"
                    };

                    var service = new GmailService(initializer);

                    string fromEmail = "*****@*****.**";
                    //string fromName = @"AdamMorgan";
                    string fromName = "";

                    /// This code ss needed to extract signed in user info (email, display name)
                    var gps = new PlusService(initializer);
                    var me  = gps.People.Get("me").Execute();
                    fromEmail = me.Emails.First().Value;
                    //fromName = me.DisplayName;
                    ////////////////////////////////////////

                    MimeMessage message = new MimeMessage();
                    message.To.Add(new MailboxAddress("", email.to));
                    if (email.cc != null)
                    {
                        message.Cc.Add(new MailboxAddress("", email.cc));
                    }
                    if (email.bcc != null)
                    {
                        message.Bcc.Add(new MailboxAddress("", email.bcc));
                    }
                    if (email.subject != null)
                    {
                        message.Subject = email.subject;
                    }

                    var addr = new MailboxAddress(fromName, fromEmail);
                    message.From.Add(addr);
                    if (email.body != null)
                    {
                        message.Body = new TextPart("html")
                        {
                            Text = email.body
                        };
                    }

                    var ms = new MemoryStream();
                    message.WriteTo(ms);
                    ms.Position = 0;
                    StreamReader sr = new StreamReader(ms);
                    Google.Apis.Gmail.v1.Data.Message msg = new Google.Apis.Gmail.v1.Data.Message();
                    string rawString = sr.ReadToEnd();

                    byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
                    msg.Raw = System.Convert.ToBase64String(raw);
                    var res = service.Users.Messages.Send(msg, "me").Execute();
                }
                return(View());
            }
            else
            {
                string redirectUri = result.RedirectUri;

                /// Remove port from the redirect URL.
                /// This action is needed for http://gmailappasp.apphb.com/ application only.
                /// Remove it if you hosted solution not on the http://gmailappasp.apphb.com/
                redirectUri = Regex.Replace(result.RedirectUri, @"(:\d{3,5})", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                ///

                return(new RedirectResult(redirectUri));
            }
        }