Exemplo n.º 1
0
        private MimeMessage GetMimeMessage(string fromId, string fromName, string toIds, string subject, string body, string[] attachments)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromName, fromId));
            message.To.Add(new MailboxAddress(toIds, toIds));
            message.Subject = subject;

            var textPartBody = new TextPart("plain")
            {
                Text = body
            };

            var multipart = new Multipart("mixed");

            multipart.Add(textPartBody);
            foreach (var att in attachments)
            {
                var extension  = Path.GetExtension(att);
                var attachment = new MimePart(MimeTypes.MimeTypeMap.GetMimeType(extension), extension)
                {
                    ContentObject           = new ContentObject(File.OpenRead(att), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = Path.GetFileName(att)
                };
                multipart.Add(attachment);
            }
            message.Body = multipart;
            return(message);
        }
Exemplo n.º 2
0
        // public async Task SendWithAttachmentAsync(string email, string subject, string mailBody, string path)
        public async Task SendWithAttachmentAsync(string email, string subject, string mailBody, string path)
        {
            //string value = _smtpConfiguration.GetSection("Smtp").GetSection("Smtp").Value;
            var data        = appSettings.Value.Port;
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(appSettings.Value.SenderName, appSettings.Value.SenderEmail));
            mimeMessage.To.Add(new MailboxAddress(email));
            mimeMessage.Subject = subject;
            var multipart = new Multipart();
            var body      = new TextPart("plain")
            {
                Text = mailBody
            };

            multipart.Add(body);
            if (path != null)
            {
                var attachment = new MimePart("application/pdf")
                {
                    Content                 = new MimeContent(File.OpenRead(path)),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = Path.GetFileName(path)
                };
                multipart.Add(attachment);
            }

            mimeMessage.Body = multipart;
            await SendAsync(mimeMessage);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Parses the "TO", "FROM", "SUBJECT", and "BODY" command line args and creates a MimeMessage instance from them
        /// </summary>
        /// <returns>The initialized MimeMessage instance</returns>
        private static MimeMessage CreateMessage()
        {
            MimeMessage Message = new MimeMessage();

            Message.To.AddRange(Recipients());
            Message.From.Add(MakeAddress(AppSettingsImpl.From));
            Message.Subject = AppSettingsImpl.Subject;
            TextPart Body = new TextPart("plain")
            {
                Text = AppSettingsImpl.Body
            };

            if (AppSettingsImpl.Attachment.Initialized)
            {
                MimePart Attachment = new MimePart("text", "plain")
                {
                    Content                 = new MimeContent(File.OpenRead(AppSettingsImpl.Attachment), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = Path.GetFileName(AppSettingsImpl.Attachment)
                };
                Multipart MultipartBody = new Multipart("mixed");
                MultipartBody.Add(Body);
                MultipartBody.Add(Attachment);
                Message.Body = MultipartBody;
            }
            else
            {
                Message.Body = Body;
            }
            return(Message);
        }
Exemplo n.º 4
0
        public void SendMail(string receiverAdress, string messageSubject, string messageBody)
        {
            var path = @"wwwroot\img\auLogo.png";
            //MailMessage mailMessage = new MailMessage();
            var mailMessage = new MimeMessage();

            mailMessage.From.Add(new MailboxAddress("*****@*****.**"));
            mailMessage.To.Add(new MailboxAddress(receiverAdress));
            mailMessage.Subject = messageSubject;

            var body = new TextPart("plain")
            {
                Text = messageBody
            };

            var attachment = new MimePart("image", "png")
            {
                ContentObject = new ContentObject(File.OpenRead(path), ContentEncoding.Base64),
                //TODO: FIX
                ContentDisposition      = new ContentDisposition(ContentDisposition.FormData),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = Path.GetFileName(path),
            };

            var multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(attachment);

            mailMessage.Body = multipart;

            client.Send(mailMessage);
            client.Disconnect(true);
        }
Exemplo n.º 5
0
        static MessagePart CreateImapExampleInnerMessageRfc822(List <MimeEntity> parents)
        {
            var message     = new MimeMessage();
            var mixed       = new Multipart("mixed");
            var alternative = new MultipartAlternative();
            var rfc822      = new MessagePart {
                Message = message
            };

            parents.Add(rfc822);
            message.Body = mixed;

            parents.Add(mixed);
            mixed.Add(new TextPart("plain"));

            parents.Add(mixed);
            mixed.Add(alternative);

            parents.Add(alternative);
            alternative.Add(new TextPart("plain"));

            parents.Add(alternative);
            alternative.Add(new TextPart("richtext"));

            return(rfc822);
        }
Exemplo n.º 6
0
        public async Task <MimeMessage> RenderAsync(MailTemplate template)
        {
            var context = new MailTemplateContext();

            // render template
            var htmlBody = await RenderAsync(template, context);

            // construct message
            var message = new MimeMessage();

            if (context.Subject != null)
            {
                message.Subject = context.Subject;
            }

            var body = new Multipart("mixed");

            body.Add(new TextPart(TextFormat.Html)
            {
                Text = htmlBody,
            });
            foreach (var bodyPart in context.BodyParts)
            {
                body.Add(bodyPart);
            }
            message.Body = body;

            return(message);
        }
Exemplo n.º 7
0
        public async Task SendWithAttachmentAsync(string email, string subject, string mailBody, string path)
        {
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_smtpConfiguration["SenderName"], _smtpConfiguration["SenderEmail"]));
            mimeMessage.To.Add(new MailboxAddress(email));
            mimeMessage.Subject = subject;
            var body = new TextPart("plain")
            {
                Text = mailBody
            };
            var attachment = new MimePart("application/pdf")
            {
                Content                 = new MimeContent(File.OpenRead(path)),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(path)
            };
            var multipart = new Multipart();

            multipart.Add(body);
            multipart.Add(attachment);
            mimeMessage.Body = multipart;
            await SendAsync(mimeMessage);
        }
Exemplo n.º 8
0
        private Multipart EncryptAndSign(Multipart input, GpgPrivateKeyInfo senderKey, GpgPublicKeyInfo recipientKey)
        {
            var gpgMultipart = new Multipart("encrypted");

            gpgMultipart.ContentType.Parameters.Add("protocol", "application/pgp-encrypted");

            var versionPart = new TextPart("pgp-encrypted");

            versionPart.ContentType.MediaType = "application";
            versionPart.Headers.Add(new Header("Content-Description", "PGP/MIME version identification"));
            versionPart.Text = "Version: 1";
            gpgMultipart.Add(input);

            var multipartStream = new MemoryStream();

            input.WriteTo(multipartStream);
            multipartStream.Position = 0;
            var plainText = Encoding.UTF8.GetString(multipartStream.ToArray()).Replace("\n", "\r\n");

            _gpg.EncryptAndSign(plainText, out string cipherText, recipientKey.Id, senderKey.Id, true, senderKey.Passphrase);
            var encryptedPart = new TextPart("octet-stream");

            encryptedPart.ContentType.MediaType       = "application";
            encryptedPart.ContentType.Name            = "encrypted.asc";
            encryptedPart.ContentDisposition          = new ContentDisposition("inline");
            encryptedPart.ContentDisposition.FileName = "encrypted.asc";
            encryptedPart.Text = cipherText;
            encryptedPart.ContentTransferEncoding = ContentEncoding.SevenBit;
            encryptedPart.Headers.Remove(HeaderId.ContentTransferEncoding);
            gpgMultipart.Add(encryptedPart);

            return(gpgMultipart);
        }
Exemplo n.º 9
0
        public static void Send(F2G.Models.File file, string receiverEmail)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("File2Go", "*****@*****.**"));
            emailMessage.To.Add(new MailboxAddress("", file.response.client.User.email));
            emailMessage.Subject = "Your File From File2Go!";
            var body = new TextPart("plain")
            {
                Text = "Here is your file, " + file.name + ", from File2Go!"
            };
            var attachment = new MimePart()
            {
                ContentObject           = new ContentObject(new MemoryStream(file.contents)),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = file.name
            };
            var multipart = new Multipart("mixed");

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

            using (var client = new SmtpClient())
            {
                client.Connect("smtp-mail.outlook.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate("*****@*****.**", "dr0wss4p");
                client.Send(emailMessage);
                client.Disconnect(true);
            }
        }
Exemplo n.º 10
0
        public Task <IMimeMessage> CreateInstance(IEnumerable <MimeHeader> headers,
                                                  IEnumerable <MimeEntity> bodyParts,
                                                  IEnumerable <MimeEntity> attachments)
        {
            var message = new global::MimeKit.MimeMessage();

            message.Headers.Clear();

            foreach (var header in headers)
            {
                message.Headers.Add(header.Field, header.Value);
            }

            var multipartMixed       = new Multipart("mixed");
            var multipartAlternative = new MultipartAlternative();

            foreach (var bodyPart in bodyParts)
            {
                multipartAlternative.Add(CreateMimePart <TextPart>(bodyPart));
            }

            multipartMixed.Add(multipartAlternative);

            foreach (var attachment in attachments)
            {
                multipartMixed.Add(CreateMimePart <MimePart>(attachment));
            }

            message.Body = multipartMixed;

            return(Task.FromResult((IMimeMessage) new MimeMessage(message)));
        }
Exemplo n.º 11
0
        private Multipart Sign(Multipart input, GpgPrivateKeyInfo senderKey)
        {
            var gpgMultipart = new Multipart("signed");

            gpgMultipart.ContentType.Parameters.Add("micalg", "pgp-sha256");
            gpgMultipart.ContentType.Parameters.Add("protocol", "application/pgp-signature");
            gpgMultipart.Add(input);

            var multipartStream = new MemoryStream();

            input.WriteTo(multipartStream);
            var signedText = Encoding.UTF8.GetString(multipartStream.ToArray()).Replace("\n", "\r\n");

            _gpg.Sign(signedText, out string signatureText, senderKey.Id, SignatureType.DetachSign, true, senderKey.Passphrase);
            var signaturePart = new TextPart("pgp-signature");

            signaturePart.ContentType.MediaType       = "application";
            signaturePart.ContentType.Name            = "signature.asc";
            signaturePart.ContentDisposition          = new ContentDisposition("attachment");
            signaturePart.ContentDisposition.FileName = "signature.asc";
            signaturePart.Text = signatureText;
            signaturePart.ContentTransferEncoding = ContentEncoding.SevenBit;
            signaturePart.Headers.Remove(HeaderId.ContentTransferEncoding);

            gpgMultipart.Add(signaturePart);

            return(gpgMultipart);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Class for sending emails
        /// </summary>
        public static void sendMail()
        {
            XmlDocument xml = new XmlDocument();

            xml.Load(Session.settingsPath);

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(
                                 xml.SelectSingleNode("/info/email/sender/name").InnerText.ToString(),
                                 xml.SelectSingleNode("/info/email/sender/address").InnerText.ToString()));

            message.Subject = xml.SelectSingleNode("/info/email/sender/subject").InnerText.ToString();

            message.To.Add(new MailboxAddress(
                               xml.SelectSingleNode("/info/email/receiver/name").InnerText.ToString(),
                               xml.SelectSingleNode("/info/email/receiver/address").InnerText.ToString()
                               ));

            using FileStream fs = File.OpenRead(Session.projectPath + @"\Resources\Graph.jpg");
            var attachment = new MimePart("image", "gif")
            {
                Content                 = new MimeContent(fs),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(Session.projectPath + @"\Resources\Graph.jpg")
            };

            var body = new TextPart("plain")
            {
                Text = @"Hey there,

                You can find new covid-19 cases in Czech Republic for last 14 days graph in the attachment.

                Yours faithfull,
                Windows Service"
            };

            var multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(attachment);

            message.Body = multipart;

            using SmtpClient client = new SmtpClient();
            client.Connect(
                xml.SelectSingleNode("/info/email/sender/smtp").InnerText.ToString(),
                Int32.Parse(xml.SelectSingleNode("/info/email/sender/port").InnerText.ToString()),
                true);
            client.Authenticate(
                xml.SelectSingleNode("/info/email/sender/address").InnerText.ToString(),
                xml.SelectSingleNode("/info/email/sender/password").InnerText.ToString()
                );
            client.Send(message);
            client.Disconnect(true);
            client.Dispose();
            fs.Close();
        }
Exemplo n.º 13
0
        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tos"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="attachments"></param>
        /// <returns></returns>
        public async static Task SendEmailAsync(Config config, List <MailAddress> tos, string subject, string message, params string[] attachments)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add((MailboxAddress)config.From);
            foreach (var to in tos)
            {
                emailMessage.To.Add(to as MailAddress);
            }

            emailMessage.Subject = subject;


            var alternative = new Multipart("alternative");

            if (config.IsHtml)
            {
                alternative.Add(new TextPart("html")
                {
                    Text = message
                });
            }
            else
            {
                alternative.Add(new TextPart("plain")
                {
                    Text = message
                });
            }

            if (attachments != null)
            {
                foreach (string f in attachments)
                {
                    var attachment = new MimePart()//("image", "png")
                    {
                        ContentObject           = new ContentObject(File.OpenRead(f), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = Path.GetFileName(f)
                    };
                    alternative.Add(attachment);
                }
            }
            emailMessage.Body = alternative;

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(config.Host, config.Port, config.UseSsl).ConfigureAwait(false);// SecureSocketOptions.None

                client.AuthenticationMechanisms.Remove("XOAUTH2");

                await client.AuthenticateAsync(config.MailFromAccount, config.MailPassword);

                await client.SendAsync(emailMessage).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Callback when the picture is taken by the Camera
        /// </summary>
        /// <param name="data"></param>
        /// <param name="camera"></param>
        public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)//2
        {
            try
            {
                var DateGenerated = System.DateTime.Now;
                var message       = new MimeMessage();
                message.From.Add(new MailboxAddress("From", "*****@*****.**"));
                message.To.Add(new MailboxAddress("To", "*****@*****.**"));
                if (!string.IsNullOrEmpty(StaticUser.Email))
                {
                    message.Cc.Add(new MailboxAddress("CC", StaticUser.Email));
                }
                message.Subject = "Снимок объекта за " + DateGenerated.ToString();

                var body = new TextPart("plain")
                {
                    Text = "Снимок объекта подготовлен в " + DateGenerated.ToString()
                };

                var attachment = new MimePart("image", "jpg")
                {
                    Content                 = new MimeContent(new MemoryStream(data), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = "снимок_объекта_" + DateGenerated.ToString() + ".jpg"
                };

                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed");
                multipart.Add(body);
                multipart.Add(attachment);
                message.Body = multipart;

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect("smtp.mail.ru", 587, false);
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate("*****@*****.**", "MKFe5ElR");
                    client.Send(message);
                    client.Disconnect(true);
                }

                //string fileName = Uri.Parse("test.jpg").LastPathSegment;
                //var os = _context.OpenFileOutput(fileName, FileCreationMode.Private);
                //System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(os);
                //binaryWriter.Write(data);
                //binaryWriter.Close();

                //We start the camera preview back since after taking a picture it freezes
                camera.StartPreview();
            }
            catch (System.Exception e)
            {
                Log.Debug(APP_NAME, "File not found: " + e.Message);
            }
        }
Exemplo n.º 15
0
        public async Task SendMailAsync(string email, string subject, string body, string path)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(smtpSettings.SenderName, smtpSettings.SenderEmail));
                message.To.Add(new MailboxAddress(email, email));
                message.Subject = subject;
                var multipart = new Multipart("mixed");
                var streams   = new List <Stream>();

                if (path != null)
                {
                    var stream     = File.OpenRead(path);
                    var attachment = new MimePart(MimeTypes.GetMimeType(path))
                    {
                        Content                 = new MimeContent(stream),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(path)
                    };
                    multipart.Add(attachment);
                    streams.Add(stream);
                }


                var html = new TextPart("html")
                {
                    Text = body,
                };

                multipart.Add(html);
                message.Body = multipart;

                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.CheckCertificateRevocation          = false;
                    await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);

                    await client.AuthenticateAsync(smtpSettings.UserName, smtpSettings.Password);

                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }

                Console.WriteLine("Email sent");
                foreach (var stream in streams)
                {
                    stream.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Email was not send {e.Message}");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Diese Methode wird aufgerufen, wenn eine Schulung angelegt wurde und generiert und schickt eine Mail an den Dozenten der Schulung.
        /// </summary>
        /// <param name="schulung">Die Schulung, die angelegt wurde</param>
        public async Task GenerateAndSendAnlegeMailAsync(Schulung schulung, string rootUrl, string vorstand)
        {
            try
            {
                MimeMessage message = new MimeMessage();
                message.From.Add(new MailboxAddress("Schulungsportal", emailSender.GetAbsendeAdresse())); //Absender
                foreach (var dozent in schulung.Dozenten)
                {
                    message.To.Add(GetSafeMailboxAddress(dozent.Name, dozent.EMail)); // Empfaenger
                }
                message.Subject = "[INFO/noreply] Schulung angelegt";                 //Betreff

                var teilnehmerListeUrl = rootUrl + "/Schulung/Teilnehmer/" + schulung.AccessToken;

                var dozentenEmails = schulung.Dozenten.Select(d => d.EMail);
                var attachments    = GetAppointment(schulung, dozentenEmails, emailSender.GetAbsendeAdresse(), istAbsage: false);

                MailViewModel mvm = new MailViewModel
                {
                    //CCLogoFile = "cclogo.png@"+Guid.NewGuid().ToString(),
                    //FacebookLogoFile = "fblogo.png@" + Guid.NewGuid().ToString(),
                    //InstaLogoFile = "instalogo.png@" + Guid.NewGuid().ToString(),
                    Schulung           = schulung,
                    Vorstand           = vorstand,
                    TeilnehmerListeUrl = teilnehmerListeUrl,
                };

                var body = new TextPart("html") //Inhalt
                {
                    Text = await RunCompileAsync("AnlegeMail", mvm),
                    ContentTransferEncoding = ContentEncoding.Base64,
                };

                var outmultipart = new Multipart("mixed");
                outmultipart.Add(body);
                //inmultipart.Add(attachments.First());
                // Bilder für Corporate Design, funktioniert leider nicht
                //outmultipart.Add(inmultipart);
                //outmultipart.Add(LoadInlinePicture("CCLogo.png", mvm.CCLogoFile));
                //outmultipart.Add(LoadInlinePicture("FBLogo.png", mvm.FacebookLogoFile));
                //outmultipart.Add(LoadInlinePicture("InstaLogo.png", mvm.InstaLogoFile));
                foreach (var attachment in attachments)
                {
                    outmultipart.Add(attachment);
                }

                message.Body = outmultipart;

                await emailSender.SendEmailAsync(message);
            }
            catch (Exception e)
            {
                logger.Error(e);
                string code = "#601";
                e = new Exception("Fehler beim Versenden der Anlegemail (" + e.Message + ") " + code, e);
                throw e;
            }
        }
Exemplo n.º 17
0
        public static void send_Gmail(string[] To, string Subject, string Body, string From_name = "", string attachment_path = null, string ContentMediaType = null, string ContentSubType = null)
        {
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(From_name, oauth2_account.mail_address));

            foreach (string str in To)
            {
                message.To.Add(new MailboxAddress("", str));
            }

            message.Subject = Subject;



            if (ContentMediaType != null)
            {
                var body = new TextPart("plain")
                {
                    Text = Body
                };

                var attachment = new MimePart(ContentMediaType, ContentSubType)
                {
                    ContentObject           = new ContentObject(File.OpenRead(attachment_path), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = Path.GetFileName(attachment_path)
                };

                var multipart = new Multipart("mixed");
                multipart.Add(body);
                multipart.Add(attachment);

                message.Body = multipart;
            }
            else
            {
                message.Body = new TextPart("plain")
                {
                    Text = Body
                };
            }

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

                client.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls);

                //client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(oauth2_account.mail_address, oauth2_account.oauth2_access_Token);

                client.Send(message);
                client.Disconnect(true);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Sends an email containing the journey details to the nominated email address.
        /// </summary>
        /// <param name="journeyName">The unique journey name.</param>
        /// <param name="simpleJourneyDetailsFilePath">The file path to the simple journey details.</param>
        /// <param name="extendedJourneyDetailsFilePath">The file path to the extended journey details.</param>
        private void SendEmail(string journeyName, string simpleJourneyDetailsFilePath, string extendedJourneyDetailsFilePath)
        {
            // Get shared preferences
            ISharedPreferences settings = _context.GetSharedPreferences("settings", 0);

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress("fleetTRACK", settings.GetString("SourceAddress", "")));
            message.To.Add(new MailboxAddress(settings.GetString("SendAddress", ""), settings.GetString("SendAddress", "")));
            message.Subject = journeyName;

            TextPart body = new TextPart("plain")
            {
                Text = "To whom it may concern,\n\tPlease see the attached trip details for billing purposes.\nKind regards,\nfleetTRACK"
            };

            // create an attachment for the file located at path
            MimePart simpleJourneyDetailsAttachment = new MimePart("text/csv")
            {
                ContentObject           = new ContentObject(File.OpenRead(simpleJourneyDetailsFilePath), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = Path.GetFileName(simpleJourneyDetailsFilePath)
            };

            // create an attachment for the file located at path
            MimePart extendedJourneyDetailsAttachment = new MimePart("text/csv")
            {
                ContentObject           = new ContentObject(File.OpenRead(extendedJourneyDetailsFilePath), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = Path.GetFileName(extendedJourneyDetailsFilePath)
            };

            // now create the multipart/mixed container to hold the message text and the attachments
            Multipart multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(simpleJourneyDetailsAttachment);
            multipart.Add(extendedJourneyDetailsAttachment);

            // now set the multipart/mixed as the message body
            message.Body = multipart;

            using (SmtpClient client = new SmtpClient())
            {
                client.Connect(settings.GetString("SmtpServer", ""), settings.GetInt("SmtpPort", 25), false);

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

                client.Authenticate(settings.GetString("SmtpUsername", ""), settings.GetString("SmtpPassword", ""));

                client.Send(message);
                client.Disconnect(true);
            }
        }
Exemplo n.º 19
0
        private static async Task TestClientConnectionAsync(MailDemonService demon, string server, string to, string file)
        {
            SmtpClient client = new SmtpClient()
            {
                SslProtocols = System.Security.Authentication.SslProtocols.None,
                Timeout      = 60000 // 60 secs
            };
            await client.ConnectAsync(server, 25, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);

            try
            {
                await client.AuthenticateAsync(new NetworkCredential("no", "no"));
            }
            catch
            {
                // expected
            }

            await client.DisconnectAsync(false);

            await client.ConnectAsync(server, 25, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);

            await client.AuthenticateAsync(new NetworkCredential(demon.Users.First().UserName, demon.Users.First().Password));

            MimeMessage msg = new MimeMessage();

            msg.From.Add(demon.Users.First().MailAddress);
            foreach (string toAddress in to.Split(',', ';'))
            {
                msg.To.Add(MailboxAddress.Parse(toAddress));
            }
            msg.Subject = "Test Subject";
            BodyBuilder bodyBuilder = new BodyBuilder();
            Multipart   multipart   = new Multipart("mixed");

            bodyBuilder.HtmlBody = "<html><body><b>Test Email Html Body Which is Bold 12345</b></body></html>";
            multipart.Add(bodyBuilder.ToMessageBody());
            if (file != null && File.Exists(file))
            {
                byte[] bytes      = System.IO.File.ReadAllBytes(file);
                var    attachment = new MimePart("binary", "bin")
                {
                    Content                 = new MimeContent(new MemoryStream(bytes), ContentEncoding.Binary),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Binary, // Base64 for DATA test, Binary for BINARYMIME test
                    FileName                = Path.GetFileName(file)
                };
                multipart.Add(attachment);
            }
            msg.Body = multipart;
            await client.SendAsync(msg);

            await client.DisconnectAsync(true);

            Console.WriteLine("Test message sent");
        }
Exemplo n.º 20
0
        public async Task SendAsync(Email emailRequest)
        {
            if (options.Enabled)
            {
                var format  = emailRequest.IsBodyHtml ? MimeKit.Text.TextFormat.Html : MimeKit.Text.TextFormat.Text;
                var builder = new BodyBuilder();

                builder.TextBody = emailRequest.Body;
                builder.HtmlBody = emailRequest.Body;

                var multipart = new Multipart("mixed");
                multipart.Add(new TextPart(format)
                {
                    Text = emailRequest.Body
                });

                if (emailRequest.FileName != null && emailRequest.Attachment != null)
                {
                    Stream stream = new MemoryStream(emailRequest.Attachment);
                    // create an image attachment for the file located at path
                    var attachment = new MimePart("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    {
                        Content                 = new MimeContent(stream),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(emailRequest.FileName)
                    };
                    multipart.Add(attachment);
                }

                var msg = new MimeMessage
                {
                    Subject = emailRequest.Subject,
                    Body    = multipart
                };

                msg.From.Add(new MailboxAddress(options.Email, options.Email));
                msg.To.Add(new MailboxAddress(emailRequest.NameTo, emailRequest.To));

                using var client = new SmtpClient();

                client.Connect(options.Host, options.Port);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                // O usar https://stackoverflow.com/a/33501052
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(options.Email, options.Password);

                await client.SendAsync(msg);

                client.Disconnect(true);
            }
        }
Exemplo n.º 21
0
        public static int SendEmail(string from, string fromTitle, string to, string toTitle, string subject, string bodyContent, string path, string yourEmail, string yourPass)
        {
            try
            {
                var body = new TextPart("plain")
                {
                    Text = bodyContent
                };

                // Smtp Server
                string SmtpServer = "smtp.gmail.com";
                // Smtp Port Number
                int SmtpPortNumber = 587;
                var mimeMessage    = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(fromTitle, from));
                mimeMessage.To.Add(new MailboxAddress(toTitle, to));
                mimeMessage.Subject = subject;


                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed");
                multipart.Add(body);

                // add attackment
                // create an image attachment for the file located at path
                if (path != "")
                {
                    var attachment = new MimePart()
                    {
                        ContentObject           = new ContentObject(System.IO.File.OpenRead(path), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = Path.GetFileName(path)
                    };
                    multipart.Add(attachment);
                }

                // now set the multipart/mixed as the message body
                mimeMessage.Body = multipart;

                using (var client = new SmtpClient())
                {
                    client.Connect(SmtpServer, SmtpPortNumber, false);
                    //client.Authenticate("your email", "your pass");

                    client.Send(mimeMessage);
                    client.Disconnect(true);
                }
                return(1);
            }
            catch
            {
                return(0);
            }
        }
Exemplo n.º 22
0
        public async Task Generate(string email, string mailTemplate, object mailData, string subject, Tuple <byte[], string>[] attachments = null)
        {
            var html = viewRender.Render(mailTemplate, mailData);

            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(mailSettings.From, mailSettings.Login));
            mimeMessage.To.Add(new MailboxAddress("", email));
            mimeMessage.Subject = subject;

            var multipart = new Multipart("mixed");

            var body = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = html
            };

            multipart.Add(body);

            if (!(attachments is null))
            {
                for (var i = 0; i < attachments.Length; i++)
                {
                    var typeAndExt = attachments[i].Item2.Split('/');
                    var file       = new MimePart(typeAndExt[0], typeAndExt[1])
                    {
                        Content                 = new MimeContent(new MemoryStream(attachments[i].Item1), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = $"Attachment{i + 1}"
                    };

                    multipart.Add(file);
                }
            }

            mimeMessage.Body = multipart;

            try
            {
                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync(mailSettings.ServiceUri, mailSettings.ServicePort, true);

                    await client.AuthenticateAsync(mailSettings.Login, mailSettings.Password);

                    await client.SendAsync(mimeMessage);

                    await client.DisconnectAsync(true);
                }
            }
            catch (System.Exception)
            {
                throw new ApiException(HttpStatusCode.Conflict, ApiError.MailServerDeclinedEmail);
            }
        }
Exemplo n.º 23
0
        public void imapSaveAttachedFile(dbData3060DataContext p_dbData3060, string filename, byte[] data, bool bTilPBS)
        {
            string local_filename = filename.Replace('.', '_') + ".txt";

            MimeMessage message = new MimeMessage();
            TextPart    body;

            message.To.Add(new MailboxAddress(@"Regnskab Puls3060", @"*****@*****.**"));
            message.From.Add(new MailboxAddress(@"Regnskab Puls3060", @"*****@*****.**"));

            if (bTilPBS)
            {
                message.Subject = "Til PBS: " + local_filename;
                body            = new TextPart("plain")
                {
                    Text = @"Til PBS: " + local_filename
                };
            }
            else
            {
                message.Subject = "Fra PBS: " + local_filename;
                body            = new TextPart("plain")
                {
                    Text = @"Fra PBS: " + local_filename
                };
            }

            var attachment = new MimePart("text", "plain")
            {
                ContentObject           = new ContentObject(new MemoryStream(data), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = local_filename
            };

            var multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(attachment);

            message.Body = multipart;

            using (var client = new ImapClient())
            {
                client.Connect("imap.gigahost.dk", 993, true);
                client.AuthenticationMechanisms.Remove("XOAUTH");
                client.Authenticate(clsApp.GigaHostImapUser, clsApp.GigaHostImapPW);

                var PBS = client.GetFolder("INBOX.PBS");
                PBS.Open(FolderAccess.ReadWrite);
                PBS.Append(message);
                PBS.Close();

                client.Disconnect(true);
            }
        }
Exemplo n.º 24
0
        ///<summary>Helper method that creates a new MIME message based on the parameters (to, cc, bcc, from, and body)</summary>
        private static MimeMessage CreateMIMEMsg(BasicEmailAddress emailAddress, BasicEmailMessage emailMessage)
        {
            MimeMessage mimeMsg   = new MimeMessage();
            Multipart   multipart = new Multipart();

            mimeMsg.From.Add(new MailboxAddress(emailAddress.EmailUsername));
            if (!emailMessage.Subject.IsNullOrEmpty())
            {
                mimeMsg.Subject = emailMessage.Subject;
            }
            //Create MailAddress objects for all addresses.
            //MailAddress will automatically parse out "DisplayName" <*****@*****.**> and every variation
            MailAddress toAddress = new MailAddress(emailMessage.ToAddress.Trim());

            mimeMsg.To.Add(new MailboxAddress(toAddress.DisplayName, toAddress.Address));
            if (!emailMessage.CcAddress.IsNullOrEmpty())
            {
                MailAddress ccAddress = new MailAddress(emailMessage.CcAddress.Trim());
                mimeMsg.Cc.Add(new MailboxAddress(ccAddress.DisplayName, ccAddress.Address));
            }
            if (!emailMessage.BccAddress.IsNullOrEmpty())
            {
                MailAddress bccAddress = new MailAddress(emailMessage.BccAddress.Trim());
                mimeMsg.Cc.Add(new MailboxAddress(bccAddress.DisplayName, bccAddress.Address));
            }
            if (emailMessage.ListAttachments != null)
            {
                foreach (Tuple <string, string> attachmentPath in emailMessage.ListAttachments)
                {
                    multipart.Add(new MimePart()
                    {
                        Content                 = new MimeContent(File.OpenRead(attachmentPath.Item1)),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(attachmentPath.Item1)
                    });
                }
            }
            if (emailMessage.IsHtml)
            {
                multipart.Add(new TextPart(MimeKit.Text.TextFormat.Html)
                {
                    Text = emailMessage.HtmlBody
                });
            }
            else
            {
                multipart.Add(new TextPart()
                {
                    Text = emailMessage.BodyText
                });
            }
            mimeMsg.Body = multipart;
            return(mimeMsg);
        }
        public void SendEmailAsync(List <string> emails, string subject, string message, List <MimePart> attachments)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("Sistema Vida Nova", "*****@*****.**"));
            emailMessage.To.Add(new MailboxAddress("", "*****@*****.**"));
            foreach (string email in emails)
            {
                emailMessage.Bcc.Add(new MailboxAddress("", email));
            }
            emailMessage.Subject = subject;
            if (attachments.Count > 0) // se contem anexos
            {
                var multipart = new Multipart("mixed");
                multipart.Add(new TextPart(TextFormat.Html)
                {
                    Text = message
                });                                 // texto da mensagem
                foreach (var attach in attachments) // anexos
                {
                    multipart.Add(attach);
                }
                emailMessage.Body = multipart;
            }
            else
            {
                emailMessage.Body = new TextPart(TextFormat.Html)
                {
                    Text = "<div>" + message + "</div>"
                };
            }


            using (var client = new SmtpClient())
            {
                //client.LocalDomain = "localhost";//colocar o dominio do sistema ex: vidanova.com.br

                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;


                client.Connect("smtp.gmail.com", 465, true);// 465 587

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


                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "Vid@nova");

                client.Send(emailMessage);
                client.Disconnect(true);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// 获取发送数据对象
        /// http://www.mimekit.net/docs/html/Introduction.htm
        /// </summary>
        /// <param name="emailModel"></param>
        /// <returns></returns>
        public MimeMessage GetMimeMessage(EmailModel emailModel, bool isUsingDefault = true)
        {
            if (isUsingDefault)
            {
                emailModel.MailFromAddress = _fromAddress;
                emailModel.MailFromUser    = _fromName;
                emailModel.Host            = _host;
                emailModel.Password        = _fromPassword;
                emailModel.Port            = _port;
            }

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(emailModel.MailFromUser, emailModel.MailFromAddress));
            message.To.Add(new MailboxAddress(emailModel.MailToUser, emailModel.MailToAddress));
            message.Subject = emailModel.Subject;

            //邮件正文
            var alternativeBody = new MultipartAlternative();
            var textBody        = new TextPart(TextFormat.Plain)
            {
                Text = emailModel.TextBody
            };
            var htmlBody = new TextPart(TextFormat.Html)
            {
                Text = emailModel.HtmlBody
            };

            alternativeBody.Add(textBody);
            alternativeBody.Add(htmlBody);
            Multipart multipart = new Multipart("mixed");

            multipart.Add(alternativeBody);

            //附件
            if (emailModel.Attachments != null && emailModel.Attachments.Count >= 0)
            {
                for (int i = 0; i < emailModel.Attachments.Count; i++)
                {
                    var      path       = emailModel.Attachments[i];
                    MimePart attachment = new MimePart()
                    {
                        Content                 = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(path)
                    };
                    multipart.Add(attachment);
                }
            }

            message.Body = multipart;
            return(message);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Diese Methode generiert und schickt eine Bestaetigungsmail an einen Nutzer, der sich zu einer Schulung angemeldet hat.
        /// </summary>
        /// <param name="anmeldung">Die Anmeldung, die beim anmelden erstellt wird.</param>
        /// <param name="schulung">Die Schulung, zu der sich der Nutzer angemeldet hat.</param>
        public async Task GenerateAndSendBestätigungsMailAsync(Anmeldung anmeldung, Schulung schulung, string vorstand, string rootUrl)
        {
            try
            {
                MimeMessage message = new MimeMessage();
                message.From.Add(new MailboxAddress(emailSender.GetAbsendeAdresse()));                                //Absender
                message.To.Add(GetSafeMailboxAddress(anmeldung.Vorname + " " + anmeldung.Nachname, anmeldung.Email)); // Empfaenger
                message.Subject = "[INFO/noreply] Schulungsanmeldung " + schulung.Titel;                              //Betreff

                var selbstmanagementUrl = rootUrl + "/Anmeldung/Selbstmanagement/" + anmeldung.AccessToken;

                var attachments = GetAppointment(schulung, new [] { anmeldung.Email }, emailSender.GetAbsendeAdresse(), istAbsage: false);

                MailViewModel mvm = new MailViewModel
                {
                    //CCLogoFile = "cclogo.png@"+Guid.NewGuid().ToString(),
                    //FacebookLogoFile = "fblogo.png@" + Guid.NewGuid().ToString(),
                    //InstaLogoFile = "instalogo.png@" + Guid.NewGuid().ToString(),
                    SelbstmanagementUrl = selbstmanagementUrl,
                    Schulung            = schulung,
                    Vorstand            = vorstand,
                };

                var body = new TextPart("html") //Inhalt
                {
                    Text = await RunCompileAsync("BestaetigungsMail", mvm),
                    ContentTransferEncoding = ContentEncoding.Base64,
                };

                var outmultipart = new Multipart("mixed");
                outmultipart.Add(body);
                //inmultipart.Add(attachments.First());
                // Bilder für Corporate Design, funktioniert leider nicht
                //outmultipart.Add(inmultipart);
                //outmultipart.Add(LoadInlinePicture("CCLogo.png", mvm.CCLogoFile));
                //outmultipart.Add(LoadInlinePicture("FBLogo.png", mvm.FacebookLogoFile));
                //outmultipart.Add(LoadInlinePicture("InstaLogo.png", mvm.InstaLogoFile));
                foreach (var attachment in attachments)
                {
                    outmultipart.Add(attachment);
                }

                message.Body = outmultipart;

                await emailSender.SendEmailAsync(message);
            } catch (Exception e)
            {
                logger.Error(e);
                string code = "#601";
                e = new Exception("Fehler beim Versenden der Bestätigungsmail (" + e.Message + ") " + code, e);
                throw e;
            }
        }
Exemplo n.º 28
0
        //SendMail("发送人名称", "*****@*****.**", "smtp.163.com", 25, "xxxxxxxxx授权码", new List<string> { { "*****@*****.**" } }, "邮件主题", @" <p>邮件文本</p> ", null, accessoryList: new List<MimePart>()
        //    {
        //        {
        //            new MimeKit.MimePart("audio","mp4")
        //            {
        //                ContentObject = new MimeKit.ContentObject(File.OpenRead("C:\\Users\\lyj\\Desktop\\图片\\下载 (5).mp4"), MimeKit.ContentEncoding.Default),
        //                ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
        //                ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
        //                FileName = Path.GetFileName("C:\\Users\\lyj\\Desktop\\图片\\下载 (5).mp4")
        //            }
        //      },
        //        {
        //            new MimeKit.MimePart("audio","mp4")
        //            {
        //                ContentObject = new MimeKit.ContentObject(File.OpenRead("C:\\Users\\lyj\\Desktop\\图片\\下载 (3).mp4"), MimeKit.ContentEncoding.Default),
        //                ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
        //                ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
        //                FileName = Path.GetFileName("C:\\Users\\lyj\\Desktop\\图片\\下载 (3).mp4")
        //            }
        //        },
        //        {
        //            new MimeKit.MimePart("image","jpg")
        //            {
        //                ContentObject = new MimeKit.ContentObject(File.OpenRead("C:\\Users\\lyj\\Desktop\\图片\\11timg.jpg"), MimeKit.ContentEncoding.Default),
        //                ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
        //                ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
        //                FileName = Path.GetFileName("C:\\Users\\lyj\\Desktop\\图片\\11timg.jpg")
        //            }
        //        }
        //});

        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="mail"></param>
        public static void SendMail(MailEntity mail)
        {
            try {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(mail.SendName, mail.SendAccountName));
                var mailboxAddressList = new List <MailboxAddress>();
                mail.ReceiverAccountNameList.ForEach(f =>
                {
                    mailboxAddressList.Add(new MailboxAddress(f, f));
                });
                message.To.AddRange(mailboxAddressList);

                message.Subject = mail.MailSubject;

                var alternative = new Multipart("alternative");
                if (!string.IsNullOrWhiteSpace(mail.SendText))
                {
                    alternative.Add(new TextPart("plain")
                    {
                        Text = mail.SendText
                    });
                }

                if (!string.IsNullOrWhiteSpace(mail.SendHtml))
                {
                    alternative.Add(new TextPart("html")
                    {
                        Text = mail.SendHtml
                    });
                }
                var multipart = new Multipart("mixed");
                multipart.Add(alternative);
                if (mail.AccessoryList != null)
                {
                    mail.AccessoryList?.ForEach(f =>
                    {
                        multipart.Add(f);
                    });
                }
                message.Body = multipart;
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect(mail.SmtpHost, mail.SmtpPort, false);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(mail.SendAccountName, mail.AuthenticatePassword);
                    client.Send(message);
                    client.Disconnect(true);
                }
            } catch (Exception ex) {
                LogUtil.Error(ex.Message);
            }
        }
Exemplo n.º 29
0
        static Multipart CreateImapExampleInnerMultipart(List <MimeEntity> parents)
        {
            var mixed = new Multipart("mixed");

            parents.Add(mixed);
            mixed.Add(new MimePart("image", "gif"));

            parents.Add(mixed);
            mixed.Add(CreateImapExampleInnerMessageRfc822(parents));

            return(mixed);
        }
Exemplo n.º 30
0
        /// <summary>
        /// 组装邮件
        /// </summary>
        /// <param name="BodyModel"></param>
        /// <returns></returns>
        public MimeMessage AssembleMailMessage(SendMailBodyModel BodyModel)
        {
            var Mail     = new MimeMessage();
            var Mailbody = new Multipart();

            Mail.Subject = BodyModel.Subject;                                             //设置邮件主题
            Mail.From.Add(new MailboxAddress(BodyModel.Sender, BodyModel.SenderAddress)); //设置发件人
            //设置抄送人
            if (BodyModel.Cc != null && BodyModel.Cc.Count > 0)
            {
                BodyModel.Cc.ForEach(m =>
                {
                    Mail.Cc.Add(new MailboxAddress(m));
                });
            }
            //设置密送人
            if (BodyModel.Bcc != null && BodyModel.Bcc.Count > 0)
            {
                BodyModel.Bcc.ForEach(m =>
                {
                    Mail.Bcc.Add(new MailboxAddress(m));
                });
            }
            //添加收件人
            BodyModel.Recipients.ForEach(m =>
            {
                Mail.To.Add(new MailboxAddress(m.ReceiveName, m.ReceiveMail));
            });
            //写入邮件内容
            var TextBody = new TextPart(BodyModel.MailBodyType);

            TextBody.SetText(Encoding.Default, BodyModel.Body);
            Mailbody.Add(TextBody);
            //添加邮件附件
            if (BodyModel.MailFiles != null && BodyModel.MailFiles.Count > 0)
            {
                BodyModel.MailFiles.ForEach(m =>
                {
                    var fileName   = Path.GetFileName(m);
                    var attachment = new MimePart()
                    {
                        Content                 = new MimeContent(File.OpenRead(m)),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = fileName,
                    };
                    Mailbody.Add(attachment);
                });
            }
            Mail.Body = Mailbody;
            return(Mail);
        }
Exemplo n.º 31
0
		public void TestArgumentExceptions ()
		{
			var multipart = new Multipart ();

			Assert.Throws<ArgumentNullException> (() => new Multipart ((MimeEntityConstructorArgs) null));
			Assert.Throws<ArgumentNullException> (() => new Multipart ((string) null));
			Assert.Throws<ArgumentNullException> (() => new Multipart ("mixed", null));
			Assert.Throws<ArgumentException> (() => new Multipart ("mixed", 5));

			Assert.Throws<ArgumentNullException> (() => multipart.Boundary = null);

			Assert.Throws<ArgumentNullException> (() => multipart.Add (null));
			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.Insert (-1, new TextPart ("plain")));
			Assert.Throws<ArgumentNullException> (() => multipart.Insert (0, null));
			Assert.Throws<ArgumentNullException> (() => multipart.Remove (null));
			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.RemoveAt (-1));

			Assert.Throws<ArgumentNullException> (() => multipart.Contains (null));
			Assert.Throws<ArgumentNullException> (() => multipart.IndexOf (null));

			Assert.Throws<ArgumentOutOfRangeException> (() => multipart[0] = new TextPart ("plain"));
			Assert.Throws<ArgumentNullException> (() => multipart[0] = null);

			Assert.Throws<ArgumentNullException> (() => multipart.Accept (null));

			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.CopyTo (new MimeEntity[0], -1));
			Assert.Throws<ArgumentNullException> (() => multipart.CopyTo (null, 0));

			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.Prepare (EncodingConstraint.SevenBit, 1));
		}
Exemplo n.º 32
0
		public void TestBasicFunctionality ()
		{
			var multipart = new Multipart ();

			Assert.IsNotNullOrEmpty (multipart.Boundary, "Boundary");
			Assert.IsFalse (multipart.IsReadOnly, "IsReadOnly");

			multipart.Boundary = "__Next_Part_123";

			Assert.AreEqual ("__Next_Part_123", multipart.Boundary);

			var generic = new MimePart ("application", "octet-stream") { ContentObject = new ContentObject (new MemoryStream ()), IsAttachment = true };
			var plain = new TextPart ("plain") { Text = "This is some plain text." };

			multipart.Add (generic);
			multipart.Insert (0, plain);

			Assert.AreEqual (2, multipart.Count, "Count");

			Assert.IsTrue (multipart.Contains (generic), "Contains");
			Assert.AreEqual (0, multipart.IndexOf (plain), "IndexOf");
			Assert.IsTrue (multipart.Remove (generic), "Remove");
			Assert.IsFalse (multipart.Remove (generic), "Remove 2nd time");

			multipart.RemoveAt (0);

			Assert.AreEqual (0, multipart.Count, "Count");

			multipart.Add (generic);
			multipart.Add (plain);

			Assert.AreEqual (generic, multipart[0]);
			Assert.AreEqual (plain, multipart[1]);

			multipart[0] = plain;
			multipart[1] = generic;

			Assert.AreEqual (plain, multipart[0]);
			Assert.AreEqual (generic, multipart[1]);

			multipart.Clear ();

			Assert.AreEqual (0, multipart.Count, "Count");
		}
Exemplo n.º 33
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                string boundary = System.Guid.NewGuid().ToString();
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                request.AllowWriteStreamBuffering = false;
                request.PreAuthenticate = true;

                Multipart content = new Multipart();
                content.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);

                content.Add("source", "pocketwit");

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    string geotag = string.Format("geotagged,geo:lat={0},geo:lon={1}", ppo.Lat, ppo.Lon);
                    content.Add("tags", geotag);
                }

                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    content.Add("message", ppo.Message);
                }

                content.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret, Twitter.OutputFormatType.XML);

                return content.UploadXML(request);
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 34
0
		/// <summary>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </remarks>
		/// <returns>The equivalent <see cref="MimeMessage"/>.</returns>
		/// <param name="message">The message.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="message"/> is <c>null</c>.
		/// </exception>
		public static MimeMessage CreateFromMailMessage (MailMessage message)
		{
			if (message == null)
				throw new ArgumentNullException ("message");

			var headers = new List<Header> ();
			foreach (var field in message.Headers.AllKeys) {
				foreach (var value in message.Headers.GetValues (field))
					headers.Add (new Header (field, value));
			}

			var msg = new MimeMessage (ParserOptions.Default, headers);
			MimeEntity body = null;

			// Note: If the user has already sent their MailMessage via System.Net.Mail.SmtpClient,
			// then the following MailMessage properties will have been merged into the Headers, so
			// check to make sure our MimeMessage properties are empty before adding them.
			if (msg.Sender == null && message.Sender != null)
				msg.Sender = (MailboxAddress) message.Sender;
			if (msg.From.Count == 0 && message.From != null)
				msg.From.Add ((MailboxAddress) message.From);
#if NET_3_5
			if (msg.ReplyTo.Count == 0 && message.ReplyTo != null)
				msg.ReplyTo.Add ((MailboxAddress) message.ReplyTo);
#else
			if (msg.ReplyTo.Count == 0 && message.ReplyToList.Count > 0)
				msg.ReplyTo.AddRange ((InternetAddressList) message.ReplyToList);
#endif
			if (msg.To.Count == 0 && message.To.Count > 0)
				msg.To.AddRange ((InternetAddressList) message.To);
			if (msg.Cc.Count == 0 && message.CC.Count > 0)
				msg.Cc.AddRange ((InternetAddressList) message.CC);
			if (msg.Bcc.Count == 0 && message.Bcc.Count > 0)
				msg.Bcc.AddRange ((InternetAddressList) message.Bcc);
			if (string.IsNullOrEmpty (msg.Subject))
				msg.Subject = message.Subject ?? string.Empty;

			switch (message.Priority) {
			case MailPriority.High:
				msg.Headers.Replace (HeaderId.Priority, "urgent");
				msg.Headers.Replace (HeaderId.Importance, "high");
				msg.Headers.Replace ("X-Priority", "1");
				break;
			case MailPriority.Low:
				msg.Headers.Replace (HeaderId.Priority, "non-urgent");
				msg.Headers.Replace (HeaderId.Importance, "low");
				msg.Headers.Replace ("X-Priority", "5");
				break;
			}

			if (!string.IsNullOrEmpty (message.Body)) {
				var text = new TextPart (message.IsBodyHtml ? "html" : "plain");
				text.SetText (message.BodyEncoding ?? Encoding.UTF8, message.Body);
				body = text;
			}

			if (message.AlternateViews.Count > 0) {
				var alternative = new Multipart ("alternative");

				if (body != null)
					alternative.Add (body);

				foreach (var view in message.AlternateViews) {
					var part = GetMimePart (view);

					if (view.BaseUri != null)
						part.ContentLocation = view.BaseUri;

					if (view.LinkedResources.Count > 0) {
						var type = part.ContentType.MediaType + "/" + part.ContentType.MediaSubtype;
						var related = new Multipart ("related");

						related.ContentType.Parameters.Add ("type", type);

						if (view.BaseUri != null)
							related.ContentLocation = view.BaseUri;

						related.Add (part);

						foreach (var resource in view.LinkedResources) {
							part = GetMimePart (resource);

							if (resource.ContentLink != null)
								part.ContentLocation = resource.ContentLink;

							related.Add (part);
						}

						alternative.Add (related);
					} else {
						alternative.Add (part);
					}
				}

				body = alternative;
			}

			if (body == null)
				body = new TextPart (message.IsBodyHtml ? "html" : "plain");

			if (message.Attachments.Count > 0) {
				var mixed = new Multipart ("mixed");

				if (body != null)
					mixed.Add (body);

				foreach (var attachment in message.Attachments)
					mixed.Add (GetMimePart (attachment));

				body = mixed;
			}

			msg.Body = body;

			return msg;
		}
Exemplo n.º 35
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("api_key", API_KEY);
                contents.Add("source", API_ORIGIN_ID);
                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                string contentType = "";
                foreach (MediaType ft in this.API_FILETYPES)
                {
                    if (ft.Extension.Equals(Path.GetExtension(ppo.Filename).Substring(1), StringComparison.InvariantCultureIgnoreCase))
                    {
                        contentType = ft.ContentType;
                        break;
                    }
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), contentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                // Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 36
0
		/// <summary>
		/// Constructs the message body based on the text-based bodies, the linked resources, and the attachments.
		/// </summary>
		/// <remarks>
		/// Combines the <see cref="Attachments"/>, <see cref="LinkedResources"/>, <see cref="TextBody"/>,
		/// and <see cref="HtmlBody"/> into the proper MIME structure suitable for display in many common
		/// mail clients.
		/// </remarks>
		/// <returns>The message body.</returns>
		public MimeEntity ToMessageBody ()
		{
			Multipart alternative = null;
			MimeEntity body = null;

			if (!string.IsNullOrEmpty (TextBody)) {
				var text = new TextPart ("plain");
				text.Text = TextBody;

				if (!string.IsNullOrEmpty (HtmlBody)) {
					alternative = new Multipart ("alternative");
					alternative.Add (text);
					body = alternative;
				} else {
					body = text;
				}
			}

			if (!string.IsNullOrEmpty (HtmlBody)) {
				var text = new TextPart ("html");
				MimeEntity html;

				text.ContentId = MimeUtils.GenerateMessageId ();
				text.Text = HtmlBody;

				if (LinkedResources.Count > 0) {
					var related = new MultipartRelated {
						Root = text
					};

					foreach (var resource in LinkedResources)
						related.Add (resource);

					html = related;
				} else {
					html = text;
				}

				if (alternative != null)
					alternative.Add (html);
				else
					body = html;
			}

			if (Attachments.Count > 0) {
				var mixed = new Multipart ("mixed");

				if (body != null)
					mixed.Add (body);

				foreach (var attachment in Attachments)
					mixed.Add (attachment);

				body = mixed;
			}

			return body ?? new TextPart ("plain") { Text = string.Empty };
		}
Exemplo n.º 37
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("api_key", TwitrPixKey);

                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename));

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Add("latitude", ppo.Lat);
                    contents.Add("longitude", ppo.Lat);
                }

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (WebException we)
            {
                StreamReader sr = new StreamReader(we.Response.GetResponseStream());
                string resp = sr.ReadToEnd();
                Console.WriteLine(resp);
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                //Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                request.PreAuthenticate = true;
                request.AllowWriteStreamBuffering = false;
                request.Timeout = 60000;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename));

                OAuth.OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);
                return contents.UploadXML(request);
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 39
0
        unsafe BoundaryType MultipartScanSubparts(Multipart multipart, byte* inbuf)
        {
            BoundaryType found;

            do {
                // skip over the boundary marker
                if (!SkipLine (inbuf))
                    return BoundaryType.Eos;

                // parse the headers
                state = MimeParserState.Headers;
                if (Step (inbuf) == MimeParserState.Error)
                    return BoundaryType.Eos;

                //if (state == ParserState.Complete && headers.Count == 0)
                //	return BoundaryType.EndBoundary;

                var type = GetContentType (multipart.ContentType);
                var entity = MimeEntity.Create (options, type, headers, false);

                if (entity is Multipart)
                    found = ConstructMultipart ((Multipart) entity, inbuf);
                else if (entity is MessagePart)
                    found = ConstructMessagePart ((MessagePart) entity, inbuf);
                else
                    found = ConstructMimePart ((MimePart) entity, inbuf);

                multipart.Add (entity);
            } while (found == BoundaryType.ImmediateBoundary);

            return found;
        }
Exemplo n.º 40
0
		/// <summary>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </remarks>
		/// <returns>The equivalent <see cref="MimeMessage"/>.</returns>
		/// <param name="message">The message.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="message"/> is <c>null</c>.
		/// </exception>
		public static MimeMessage CreateFromMailMessage (MailMessage message)
		{
			if (message == null)
				throw new ArgumentNullException ("message");

			var headers = new List<Header> ();
			foreach (var field in message.Headers.AllKeys) {
				foreach (var value in message.Headers.GetValues (field))
					headers.Add (new Header (field, value));
			}

			var msg = new MimeMessage (ParserOptions.Default, headers);
			MimeEntity body = null;

			if (message.Sender != null)
				msg.Sender = (MailboxAddress) message.Sender;
			if (message.From != null)
				msg.From.Add ((MailboxAddress) message.From);
			msg.ReplyTo.AddRange ((InternetAddressList) message.ReplyToList);
			msg.To.AddRange ((InternetAddressList) message.To);
			msg.Cc.AddRange ((InternetAddressList) message.CC);
			msg.Bcc.AddRange ((InternetAddressList) message.Bcc);
			msg.Subject = message.Subject ?? string.Empty;

			switch (message.Priority) {
			case MailPriority.High:
				msg.Headers.Add (HeaderId.Priority, "urgent");
				msg.Headers.Add (HeaderId.Importance, "high");
				msg.Headers.Add ("X-Priority", "1");
				break;
			case MailPriority.Low:
				msg.Headers.Add (HeaderId.Priority, "non-urgent");
				msg.Headers.Add (HeaderId.Importance, "low");
				msg.Headers.Add ("X-Priority", "5");
				break;
			}

			if (message.Body != null) {
				var text = new TextPart (message.IsBodyHtml ? "html" : "plain");
				text.SetText (message.BodyEncoding ?? Encoding.UTF8, message.Body);
				body = text;
			}

			if (message.AlternateViews.Count > 0) {
				var alternative = new Multipart ("alternative");

				if (body != null)
					alternative.Add (body);

				foreach (var view in message.AlternateViews) {
					var part = GetMimePart (view);

					if (view.BaseUri != null)
						part.ContentLocation = view.BaseUri;

					if (view.LinkedResources.Count > 0) {
						var type = part.ContentType.MediaType + "/" + part.ContentType.MediaSubtype;
						var related = new Multipart ("related");

						related.ContentType.Parameters.Add ("type", type);

						if (view.BaseUri != null)
							related.ContentLocation = view.BaseUri;

						related.Add (part);

						foreach (var resource in view.LinkedResources) {
							part = GetMimePart (resource);

							if (resource.ContentLink != null)
								part.ContentLocation = resource.ContentLink;

							related.Add (part);
						}

						alternative.Add (related);
					} else {
						alternative.Add (part);
					}
				}

				body = alternative;
			}

			if (message.Attachments.Count > 0) {
				var mixed = new Multipart ("mixed");

				if (body != null)
					mixed.Add (body);

				foreach (var attachment in message.Attachments)
					mixed.Add (GetMimePart (attachment));

				body = mixed;
			}

			msg.Body = body;

			return msg;
		}
Exemplo n.º 41
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;
                request.Headers.Add("Action", "upload");

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("key", APPLICATION_NAME);

                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    contents.Add("message", ppo.Message);
                    string hashTags = FindHashTags(ppo.Message, ",", 32);
                    if (!string.IsNullOrEmpty(hashTags))
                    {
                        contents.Add("tags", hashTags);
                    }
                }
                else
                {
                    contents.Add("message", "");
                }

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Add("latlong", string.Format("{0},{1}", ppo.Lat, ppo.Lon));
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, _account.OAuth_token, _account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (WebException ex)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, API_ERROR_UPLOAD, String.Format("Received response {0} from server ({1})", ex.Status, ex.Message)));
                return null;
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("key", TwitPicKey);

                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (Exception /*e*/)
            {
                //Socket exception 10054 could occur when sending large files.
                // Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 60000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("source", "PockeTwit");
                contents.Add("sourceLink", "http://code.google.com/p/pocketwit/");
                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    contents.Add("message", ppo.Message);
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);
                return contents.UploadXML(request);
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                {
                    using(HttpWebResponse response = ex.Response as HttpWebResponse)
                    {
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, String.Format(PockeTwit.Localization.XmlBasedResourceManager.GetString("Error Uploading: Service returned message '{0}'"), response.StatusDescription), ppo.Filename));
                    }
                }
                else if (ex.InnerException is System.Net.Sockets.SocketException)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ex.Message, ppo.Filename));
                }
                else
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD, ppo.Filename));
                return null;
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// Post a picture
        /// </summary>
        /// <param name="postData"></param>
        public virtual Uri UploadAttachment(UploadAttachment Attachment, Twitter.Account account)
        {
            if(string.IsNullOrEmpty(account.OAuth_token) || string.IsNullOrEmpty(account.OAuth_token_secret))
                throw new InvalidOperationException(Localization.XmlBasedResourceManager.GetString("No credentials supplied"));
            using (Stream contentStream = Attachment.GetStream())
            {
                if (contentStream == null)
                    throw new InvalidOperationException(Localization.XmlBasedResourceManager.GetString("Unable to open file"));

                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(API_UPLOAD);
                request.Timeout = 60000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("source", "PockeTwit");
                contents.Add("sourceLink", "http://code.google.com/p/pocketwit/");
                if (!string.IsNullOrEmpty(Attachment.Caption))
                    contents.Add("message", Attachment.Caption);

                contents.Add("media",
                    contentStream,
                    Path.GetFileName(Attachment.Name),
                    (Attachment.MediaType != null) ?
                        Attachment.MediaType.ContentType
                        : string.Empty
                );

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                XmlDocument uploadResult = contents.UploadXML(request);
                if (uploadResult == null)
                    throw new InvalidOperationException("Error parsing result");
                return new Uri(uploadResult.SelectSingleNode("//url").InnerText);
            }
        }