private static void SendIt(BaseClientService.Initializer initializer)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                ContentType = "text/html",
                Subject     = "Your Subject",
                Body        = @"<html>
<body>
Hello <strong>World!</strong>
</body>
</html>",
                From        = new MailAddress("*****@*****.**")
            };

            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            var gmail  = new GmailService(initializer);
            var result = gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();

            Console.WriteLine("Message ID {0} sent.", result.Id);
        }
Esempio n. 2
0
        public static void SendIt(string message, string emailSender)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = "BinanceAPI Message",
                Body    = message,
                From    = new MailAddress(emailSender)
            };

            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            var gmail = GService();

            var result = gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();

            Console.WriteLine("Message ID {0} sent.", result.Id);
        }
Esempio n. 3
0
        public static void SendIt(EMail email)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = email.Subject,
                Body    = email.Body,
                From    = new MailAddress(UserName)
            };

            msg.To.Add(new MailAddress(email.ToEmailAddress));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);
            // Context is a separate bit of code that provides OAuth context;
            // your construction of GmailService will be different from mine.
            if (_service == null)
            {
                _service = new GMailService();
            }
            _service.Service.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, UserName).Execute();
        }
Esempio n. 4
0
        public void SendIt(string From, string To, string Subject, string Body)
        {
            System.Diagnostics.Debug.WriteLine("TRYING TO SEND IT. FROM IS --" + From + "-- AND TO IS --" + To + "--");
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = Subject,
                Body    = Body,
                From    = new MailAddress(From)
            };

            msg.To.Add(new MailAddress(To));
            msg.ReplyTo.Add(msg.From);
            var msgStr = new StringWriter();

            msg.Save(msgStr);
            var gmail = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            var result = gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();

            Console.WriteLine("Message ID {0} sent.", result.Id);
        }
Esempio n. 5
0
        public async Task SendEmail(EmailContent model, CancellationToken cancellationToken)
        {
            if (await checkCredential())
            {
                //send email
                var msg = new AE.Net.Mail.MailMessage
                {
                    Subject = model.subject,
                    Body    = model.body,

                    From = new MailAddress(emailAddress),
                };
                string Mails      = model.to;
                var    recipients = Mails.Split(' ');
                //var recipients = new[] { model.to};
                foreach (var recipient in recipients)
                {
                    msg.To.Add(new MailAddress(recipient));
                    msg.ReplyTo.Add(msg.From);
                    var msgStr = new StringWriter();
                    msg.Save(msgStr);
                    await service.Users.Messages.Send(new Message()
                    {
                        Raw = Base64UrlEncode(msgStr.ToString())
                    }, "me").ExecuteAsync();
                }
            }
        }
        public void Notify(ScheduledEvent ev)
        {
            string text = String.Join(Environment.NewLine, "It's time for " + ev.Name);

            if (ev.Description != "")
            {
                text = String.Join(Environment.NewLine, text, "Description:", ev.Description);
            }
            if (ev.Place != "")
            {
                text = String.Join(Environment.NewLine, text, "Place:", ev.Place);
            }
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = "Notification",
                Body    = text,
                From    = new MailAddress(mail)
            };

            msg.To.Add(new MailAddress(mail));
            msg.ReplyTo.Add(msg.From);
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            var gmail  = service;
            var result = gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();
        }
        public async Task SendMailAsync(string accessToken, string subject, string to, string body, string from)
        {
            var service = new GmailService(new BaseClientService.Initializer
            {
                HttpClientInitializer = GoogleCredential.FromAccessToken(accessToken),
            });

            //send email
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body    = body,

                From = new MailAddress(from),
            };
            string Mails      = to;
            var    recipients = Mails.Split(' ');

            foreach (var recipient in recipients)
            {
                msg.To.Add(new MailAddress(recipient));
                msg.ReplyTo.Add(msg.From);
                var msgStr = new StringWriter();
                msg.Save(msgStr);
                await service.Users.Messages.Send(new Message()
                {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").ExecuteAsync();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Tries 5 times to sends a mail indicating the status of the program to the specified address. Returns whether it was successful
        /// <para>This method does NOT print information to the console.</para>
        /// </summary>
        /// <param name="address">The mail address to send status data to</param>
        /// <returns>Whether the mail was sent successfully</returns>
        public static bool SendStatusTo(String address)
        {
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    StringBuilder builder = new StringBuilder(512);
                    IAction[]     actions = Program.queue.ToArray();
                    builder.Append("A PaintDrawer Status Request was recieved from this address.\r\nQueue<IAction>().ToArray() returned: {");
                    for (int a = 0; a < actions.Length; a++)
                    {
                        builder.Append("    ");
                        builder.Append(actions[a].ToString());
                        builder.Append("\r\n");
                    }
                    builder.Append("}\r\nThat is a total of ");
                    builder.Append(actions.Length);
                    builder.Append(" IAction-s.\r\n\r\n");

                    builder.Append("Program.Time = ");
                    builder.Append(Program.Time);

                    builder.Append("\r\nProgram.LastDraw = ");
                    builder.Append(Program.LastDraw);

                    builder.Append("\r\nAccount.LastMailRecieved = ");
                    builder.Append(Account.LastMailRecieved);

                    builder.Append("\r\nAccount.LastRead = ");
                    builder.Append(Account.LastRead);

                    builder.Append("\r\nAccount.LastSuccessfullRead = ");
                    builder.Append(Account.LastSuccessfullRead);

                    var msg = new AE.Net.Mail.MailMessage
                    {
                        Subject = "PaintDrawer Status Request",
                        Body    = builder.ToString(),
                        From    = new MailAddress(MyMailAddress)
                    };
                    msg.To.Add(new MailAddress(address));
                    msg.ReplyTo.Add(msg.From); // Bounces without this!!
                    var msgStr = new StringWriter();
                    msg.Save(msgStr);

                    GmailService gmail  = Account.service;
                    Message      result = gmail.Users.Messages.Send(new Message {
                        Raw = _base64UrlEncode(msgStr.ToString())
                    }, "me").Execute();

                    return(true);
                }
                catch //(Exception e)
                {
                }
            }

            return(false);
        }
Esempio n. 9
0
        private static Message ConvertToGmailMessage(AE.Net.Mail.MailMessage message)
        {
            var msgStr = new StringWriter();

            message.Save(msgStr);
            return(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            });
        }
Esempio n. 10
0
        public static void SendIt()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials_gmail.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);
            }

            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = "Your Subject",
                Body    = getBody(),
                From    = new MailAddress("*****@*****.**")
            };

            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            var gmail = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            var result = gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();
            List <MailAddress> list = msg.To.ToList <MailAddress>();

            Console.WriteLine("Message ID {0} sent. All Reciepents {1}", result.Id, msg.To.AsEnumerable <MailAddress>().ToString());
            foreach (MailAddress ma in msg.To.ToList <MailAddress>())
            {
                Console.WriteLine("Receiver : " + ma.Address + " ," + ma.DisplayName + " ," + ma.Host + ", " + ma.User + " ," + ma.ToString());
            }
            Console.Read();
        }
Esempio n. 11
0
        public async Task <ActionResult> Compose(EmailViewModel model)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata(_authTokenService)).
                         AuthorizeAsync(CancellationToken.None);

            if (result.Credential == null)
            {
                return(new RedirectResult(result.RedirectUri));
            }
            else
            {
                var service = new GmailService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = "Gmail webapp"
                });

                var msg = new AE.Net.Mail.MailMessage
                {
                    ContentType = "text/plain",
                    Subject     = model.Subject,
                    Body        = model.Body,
                    From        = new MailAddress(model.From)
                };

                var toAddresses = model.To.Split(',');
                foreach (var to in toAddresses)
                {
                    msg.To.Add(new MailAddress(to));
                }

                var ccAddresses = model.Cc.Split(',');
                foreach (var cc in ccAddresses)
                {
                    msg.Cc.Add(new MailAddress(cc));
                }

                var BccAddresses = model.Bcc.Split(',');
                foreach (var bcc in BccAddresses)
                {
                    msg.Bcc.Add(new MailAddress(bcc));
                }
                msg.ReplyTo.Add(msg.From);

                var msgStr = new StringWriter();
                msg.Save(msgStr);

                service.Users.Messages.Send(new Message
                {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();

                return(RedirectToAction("Inbox"));
            }
        }
Esempio n. 12
0
        public BaseReturn <bool> sendMailReply(Email mail, string replymessage)
        {
            BaseReturn <bool> baseObject = new BaseReturn <bool>();

            try
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                var enc1252 = Encoding.GetEncoding(1252);

                mail.To   = mail.From;
                mail.From = Config.serviceMailId;
                mail.Body = replymessage;


                var msg = new AE.Net.Mail.MailMessage
                {
                    Subject     = "RE : " + mail.Subject,
                    Body        = mail.Body,
                    ContentType = "text/html",
                    From        = new MailAddress(mail.From)
                };

                msg.To.Add(new MailAddress(mail.To));

                msg.ReplyTo.Add(new MailAddress(mail.From));

                mail.CC.Split(',').ToList().ForEach(addr =>
                {
                    if (addr.Trim() != "")
                    {
                        msg.Cc.Add(new MailAddress(addr));
                    }
                });

                var msgStr = new StringWriter();
                msg.Save(msgStr);

                var result = _service.Users.Messages.Send(new Message
                {
                    ThreadId = mail.MailId,
                    Id       = mail.MailId,
                    Raw      = CommonFunctions.Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();

                saveReplyMailInfo(mail);
                baseObject.Success = true;
                baseObject.Data    = true;
            }
            catch (Exception ex)
            {
                baseObject.Success = false;
                baseObject.Message = "Error Occured.";
            }
            return(baseObject);
        }
Esempio n. 13
0
        public void SendMail(string To, string Subject, string Body)
        {
            UserCredential credential;
            var            PathToClientSecret = System.Web.HttpContext.Current.Request.MapPath("~\\Content\\client_secret.json");

            //using (var stream =
            //    new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            //{
            using (var stream =
                       new FileStream(PathToClientSecret, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/client_secret.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,
            });

            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = "=?UTF-8?B?" + Base64UrlEncode(Subject) + "?=",

                Body        = Body,
                From        = new MailAddress("*****@*****.**"),
                ContentType = "text/html"
            };

            msg.To.Add(new MailAddress(To));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);



            UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me");

            var resultado = request.Execute();
        }
Esempio n. 14
0
        /// <summary>
        /// Tries 5 times to send a mail indicating the valid characters. Returns whether it was successful
        /// <para>This method does NOT print information to the console.</para>
        /// </summary>
        /// <param name="address">The mail address to send valid char data to</param>
        /// <returns>Whether the mail was sent successfully</returns>
        public static bool SendValidCharsTo(String address)
        {
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    StringBuilder builder = new StringBuilder(512);
                    builder.Append("Valid Characters: \r\n");

                    for (int ci = 0; ci < PaintDrawer.Letters.CharFont.MaxCharNumericValue; ci++)
                    {
                        char c = (char)ci;
                        if (Program.font.DoesCharExist(c))
                        {
                            builder.Append("\r\nChar ");
                            builder.Append(ci);
                            builder.Append("; '");
                            builder.Append(c);
                            builder.Append("'.");
                        }
                    }

                    builder.Append("Keep in mind these are encoded in UTF-16, which is the format chosen by the .NET Framework.");

                    var msg = new AE.Net.Mail.MailMessage
                    {
                        Subject = "PaintDrawer Valid Characters Request",
                        Body    = builder.ToString(),
                        From    = new MailAddress(MyMailAddress)
                    };
                    msg.To.Add(new MailAddress(address));
                    msg.ReplyTo.Add(msg.From); // Bounces without this!!
                    var msgStr = new StringWriter();
                    msg.Save(msgStr);

                    GmailService gmail  = Account.service;
                    Message      result = gmail.Users.Messages.Send(new Message {
                        Raw = _base64UrlEncode(msgStr.ToString())
                    }, "me").Execute();

                    return(true);
                }
                catch
                {
                }
            }

            return(false);
        }
Esempio n. 15
0
        public bool SendMail(string sendTo, string messageSubject, string messageBody)
        {
            bool retVal = false;

            try
            {
                var msg = new AE.Net.Mail.MailMessage
                {
                    Subject = messageSubject,
                    Body    = messageBody,
                    From    = new MailAddress(sendingUserEmail)
                };
                msg.To.Add(new MailAddress(sendTo));
                msg.ReplyTo.Add(msg.From);
                var msgStr = new StringWriter();
                msg.Save(msgStr);

                UserCredential credential;
                string         path = HttpContext.Current.Server.MapPath("\\");
                using (var stream = new FileStream($"{path}credentials.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = $"{path}token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        sendingUserEmail,
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                }

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

                var result = gmailService.Users.Messages.Send(new Message {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();
                Console.WriteLine("Message ID {0} sent.", result.Id);
            }
            catch (Exception ex)
            {
                ErrorDescription = ex.Message;
            }
            return(retVal);
        }
Esempio n. 16
0
        public int TakeFood(FoodModel food, string email)
        {
            Food foodTaken = db.Foods.SingleOrDefault(x => x.Guid == food.GuidLine);

            foodTaken.TakenBy = db.Users.SingleOrDefault(x => x.Email == email).ID;
            try
            {
                db.SubmitChanges();

                var msg = new AE.Net.Mail.MailMessage {
                    Subject = "Someone just took your food!", Body = $"Someone just got interested in your offer and took the food. You can contact him/her via this email address: {email}", From = new MailAddress("*****@*****.**")
                };

                msg.To.Add(new MailAddress(foodTaken.User.Email));
                msg.ReplyTo.Add(msg.From);
                var msgStr = new StringWriter();
                msg.Save(msgStr);
                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);
                }
                var gmail = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential, ApplicationName = ApplicationName
                });
                var result = gmail.Users.Messages.Send(new Message
                {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();
            }
            catch (Exception e)
            {
                return(0);
            }
            return(1);
        }
Esempio n. 17
0
            //Defines content of email as well as sends out the email. Autentication with Gmail.
            public static void SendIt()
            {//Defines Email content
                var msg = new AE.Net.Mail.MailMessage
                {
                    Subject = "Onekama Voucher Program",
                    Body    = "A voucher with serial number " + VoucherForm.serial + " for $" + VoucherForm.amount + " has been created.",
                    From    = new MailAddress("*****@*****.**")
                };

                msg.To.Add(new MailAddress("*****@*****.**"));
                msg.ReplyTo.Add(msg.From); // Fills in required field, from.
                var msgStr = new StringWriter();

                msg.Save(msgStr);

                //Gmail Authentication
                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,
                        "admin",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }

                var gmail = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });
                var result = gmail.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message
                {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();

                MessageBox.Show("Voucher was Created.", "Success! You're A Winner! Don't you ever forget that.");
            }
Esempio n. 18
0
        private string ConstructRawMessage()
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = TextBoxSubject.Text,
                Body    = MsgTextBox.Text,
                From    = new MailAddress(Credentials.Email)
            };

            msg.To.Add(new MailAddress(TextBoxTo.Text));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            ContructRawAttacments(msg);
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            return(AppCode.Encoding.Base64UrlEncode(msgStr.ToString()));
        }
Esempio n. 19
0
        public void DoFormatMail(Mail mail)
        {
            StringBuilder stringBuilder = new StringBuilder();

            AE.Net.Mail.MailMessage mailMessage = new AE.Net.Mail.MailMessage();

            AE.Net.Mail.Attachment asdf = new AE.Net.Mail.Attachment();

            //MailTemplate pull

            CompositeIterator iterator     = (CompositeIterator)mail.CreateIterator();
            MailTemplate      mailTemplate = (MailTemplate)iterator.First();


            //AttachmentBox pull
            iterator = (CompositeIterator)mailTemplate.CreateIterator();
            Attachments attachmentBox = (Attachments)iterator.First();

            //Attachments pull

            iterator = (CompositeIterator)attachmentBox.CreateIterator();

            while (!iterator.IsDone())
            {
                models.components.Attachment attachment = (models.components.Attachment)iterator.CurrentItem();
                mailMessage.Attachments.Add(new AE.Net.Mail.Attachment
                {
                    Body = attachment.GetFileDirectory()
                });
            }


            mailMessage.To.Add(new MailAddress(mail.TargetMail));
            mailMessage.Subject = mailTemplate.Subject;
            mailMessage.Body    = mailTemplate.Body;
            var msgStr = new StringWriter();

            mailMessage.Save(msgStr);


            mail.FormatedMail = msgStr.ToString();
        }
        private Message CreateMessage(string to, string subject = "", string body = "")
        {
            var newEmail = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body    = body,
                From    = new MailAddress("*****@*****.**", "Keyser Soze")
            };

            newEmail.To.Add(new MailAddress(to));
            newEmail.ReplyTo.Add(newEmail.From);
            var emailString = new StringWriter();

            newEmail.Save(emailString);
            Message email = new Message {
                Raw = Encoder.ConvertToBase64(emailString.ToString())
            };

            return(email);
        }
Esempio n. 21
0
        public Message createMessage(string subject
                                     , string body
                                     , string fromMail
                                     , string toMail)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body    = body,
                From    = new MailAddress(fromMail)
            };

            msg.To.Add(new MailAddress(toMail));

            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);
            return(new Message {
                Raw = Base64UrlEncode(msgStr.ToString())
            });
        }
Esempio n. 22
0
        private void zendEmail(GmailService gs, string to, string sub, string body)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = textBox2.Text,
                Body    = textBox3.Text,
                From    = new MailAddress("*****@*****.**")
            };

            msg.To.Add(new MailAddress(textBox1.Text));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);


            var result = gs.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();

            Console.WriteLine("Message ID {0} sent.", result.Id);
        }
Esempio n. 23
0
        public void sendEmail(MailMessage mailMessage)
        {
            GmailService service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = getGmailCred()
            });


            // I really hate having to use this, but Microsoft doesn't let the average user
            // get at the raw RFC 2822 whatever internals.  So...
            // TODO:  Standardize w/o external library
            AE.Net.Mail.MailMessage msg = new AE.Net.Mail.MailMessage
            {
                Subject = mailMessage.Subject,
                Body    = mailMessage.Body,
                From    = mailMessage.From
            };

            foreach (MailAddress addr in mailMessage.To)
            {
                msg.To.Add(addr);
            }

            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(msgStr.ToString());

            var result = service.Users.Messages.Send(new Message
            {
                Raw = Convert.ToBase64String(bytes)
                      .Replace('+', '-')
                      .Replace('/', '_')
                      .Replace("=", "")
            }, "me").Execute();
        }
Esempio n. 24
0
        public void sendEmail(string email, string subject, string body)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body    = body,
                From    = new MailAddress(SenderMail)
            };

            msg.To.Add(new MailAddress(email));
            msg.ReplyTo.Add(msg.From);
            var msgStr = new StringWriter();

            msg.Save(msgStr);


            var gmail  = gmailService;
            var result = gmail.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();

            Console.WriteLine("Message ID {0} sent.", result.Id);
        }
        internal static void EnvoyerMail(MailAddress destinataire, string sujet, string corps)
        {
            var fromAddress = new MailAddress("*****@*****.**", "the best");


            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = sujet,
                Body    = corps,
                From    = fromAddress
            };

            msg.To.Add(destinataire);
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            var result = MailService.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me").Execute();

            Console.WriteLine("Message ID {0} envoyé.", result.Id);
        }
Esempio n. 26
0
        public string sendMessage(string emailAdress, string destEmail, string subject, string body, List <string> attachments)
        {
            try
            {
                var msg = new AE.Net.Mail.MailMessage
                {
                    Subject = subject,
                    Body    = body,
                    From    = new MailAddress(emailAdress)
                };

                foreach (string path in attachments)
                {
                    byte[] bytes = File.ReadAllBytes(path);
                    AE.Net.Mail.Attachment file = new AE.Net.Mail.Attachment(bytes, GetMimeType(path), Path.GetFileName(path), true);
                    msg.Attachments.Add(file);
                }

                msg.To.Add(new MailAddress(destEmail));
                msg.ReplyTo.Add(msg.From); // Bounces without this!!
                var msgStr = new StringWriter();
                msg.Save(msgStr);

                var result = service.Users.Messages.Send(new Message
                {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();
                Console.WriteLine("{0} : Message sent to {1}.", DateTime.Now, destEmail);
                return(DateTime.Now + " : Message sent to : " + destEmail + ".");
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return("An error occurred: " + e.Message);
            }
        }
Esempio n. 27
0
        public void SendEmail(User user, string subject, string text)
        {
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = subject,
                Body = text,
                From = new MailAddress(config.NotificationAccount)
            };
            msg.To.Add(new MailAddress(user.Email));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();
            msg.Save(msgStr);

            var m = new Message { Raw = Base64UrlEncode(msgStr.ToString()) };
            gmailService.Value.Users.Messages.Send(m, "me").Execute();
        }
Esempio n. 28
0
        public void SendMail()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/client_secret.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,
            });

            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = "Test GMail API Send Mail",
                Body    = "Hello, World, from Gmail API!",
                From    = new MailAddress("*****@*****.**")
            };

            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.ReplyTo.Add(msg.From); // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);


            // Define parameters of request.
            //UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

            UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())
            }, "me");

            // List labels.
            //IList<Label> labels = request.Execute().Labels;

            //Console.WriteLine("Labels:");
            //if (labels != null && labels.Count > 0)
            //{
            //    foreach (var labelItem in labels)
            //    {
            //        Console.WriteLine("{0}", labelItem.Name);
            //    }
            //}
            //else
            //{
            //    Console.WriteLine("No labels found.");
            //}
            var resultado = request.Execute();

            Console.WriteLine("Mensaje enviado " + resultado.Id);
            Console.ReadKey();
        }
Esempio n. 29
0
        /// <summary>
        /// Sends an email to an array of recipients
        /// </summary>
        /// <remarks>
        /// Inspired by: https://developers.google.com/gmail/api/guides/sending
        /// </remarks>
        public void SendEmail()
        {
            // Check to see if there's the client secret file in the proper location before continuing on to send the email
            if (!File.Exists(ClientSecret))
            {
                throw new Exception("Client Secret JSON file is missing from the application.");
            }

            // Checks to verify the email has a body, subject, from address, and an array of recipients
            if ((Body == null) || (Subject == null) || (Recipients == null) || (FromAddress == null))
            {
                throw new Exception("The email has not been formatted properly.  Be sure to include a body, subject, fromAddress, and an array of recipients.");
            }

            // Verify client credentials using client_secret.json file.
            UserCredential credential;

            // Make sure client_secret.json is the specified location
            using (FileStream stream = new FileStream(ClientSecret, 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;

                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.
            UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

            // Inspired by: https://stackoverflow.com/questions/24728793/creating-a-message-for-gmail-api-in-c-sharp
            // Creates a message with the provided list of recipients, subject, and body that were passed into the method
            var msg = new AE.Net.Mail.MailMessage
            {
                Subject = Subject,
                Body    = Body,
                From    = new MailAddress(FromAddress)
            };

            // Loops through all the values in the recipients array and adds them to the email
            foreach (var recipient in Recipients)
            {
                msg.To.Add(new MailAddress(recipient));
            }

            // Adds the return address
            msg.ReplyTo.Add(msg.From);             // Bounces without this!!
            var msgStr = new StringWriter();

            msg.Save(msgStr);

            // Sends an email message using the provided list of recipients, subject, and body that were passed into the method
            service.Users.Messages.Send(new Message
            {
                Raw = Base64UrlEncode(msgStr.ToString())                  // Make sure to Base64Encode the message, otherwise it will fail
            }, "me").Execute();
        }
        /// <summary>
        /// Send mail service
        /// </summary>
        internal void SendMail()
        {
            MailSecrets mailSecret = null;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("IpAddressGetTrayApplication.MyCredentials.mail_secrets.json"))
            {
                Json.JsonSerializer    serializer   = new Json.JsonSerializer();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);
                Json.JsonTextReader    reader       = new Json.JsonTextReader(streamReader);
                mailSecret = serializer.Deserialize <MailSecrets>(reader);
            }

            try
            {
                var    fromAddress = new MailAddress(mailSecret.Email, mailSecret.Name);
                var    toAddress   = new MailAddress(mailSecret.Email, mailSecret.Name);
                string body        = CheckIpAddress();

                var msg = new AE.Net.Mail.MailMessage
                {
                    Subject = "Adresse",
                    Body    = CheckIpAddress(),
                    From    = fromAddress
                };
                msg.To.Add(toAddress);
                msg.ReplyTo.Add(msg.From); // Bounces without this!!
                var msgStr = new System.IO.StringWriter();
                msg.Save(msgStr);

                var result = this.gmailService.Users.Messages.Send(new Message
                {
                    Raw = Base64UrlEncode(msgStr.ToString())
                }, "me").Execute();
                Logger.Log.WriteLog("Email sent");
            }
            catch (Exception err)
            {
                Logger.Log.WriteLog(err);
            }

            #region With unauthorized application

            // //Need to allow unauthorized applications in Google account
            //using(var smtp = new SmtpClient())
            //{
            //   smtp.Host = "smtp.gmail.com";
            //   smtp.Port = 587;
            //   smtp.EnableSsl = true;
            //   smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            //   smtp.UseDefaultCredentials = false;
            //   smtp.Timeout = 10000;
            //   smtp.Credentials = new NetworkCredential(fromAddress.Address, mailSecret.Password);

            //   using(var message = new MailMessage(fromAddress, toAddress))
            //   {
            //      message.Subject = subject;
            //      message.Body = body;
            //      message.IsBodyHtml = true;
            //      try
            //      {
            //         smtp.Send(message);
            //         if(this.currentWindowState == System.Windows.WindowState.Normal)
            //         {
            //            MessageBox.Show("eMail sent", "", MessageBoxButton.OK, MessageBoxImage.Information);
            //         }
            //      }
            //      catch(Exception ep)
            //      {
            //         MessageBox.Show("Exception Occured:" + ep.Message, "Send Mail Error", MessageBoxButton.OK, MessageBoxImage.Error);
            //      }
            //   }
            //}

            #endregion With unauthorized application
        }