public WriteTo ( MimeKit.FormatOptions options, Stream stream, |
||
options | MimeKit.FormatOptions | The formatting options. |
stream | Stream | The output stream. |
cancellationToken | A cancellation token. | |
리턴 | void |
public async Task<ActionResult> Index(CancellationToken cancellationToken, GmailFormModel email) { //return View(); var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); AuthorizationCodeMvcApp o = new AuthorizationCodeMvcApp(this, new AppFlowMetadata()); if (result.Credential != null) { if (email.to != null) { BaseClientService.Initializer initializer = new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "ASP.NET MVC Sample5" }; var service = new GmailService(initializer); string fromEmail = "*****@*****.**"; //string fromName = @"AdamMorgan"; string fromName = ""; /// This code ss needed to extract signed in user info (email, display name) var gps = new PlusService(initializer); var me = gps.People.Get("me").Execute(); fromEmail = me.Emails.First().Value; //fromName = me.DisplayName; //////////////////////////////////////// MimeMessage message = new MimeMessage(); message.To.Add(new MailboxAddress("", email.to)); if (email.cc != null) message.Cc.Add(new MailboxAddress("", email.cc)); if (email.bcc != null) message.Bcc.Add(new MailboxAddress("", email.bcc)); if (email.subject != null) message.Subject = email.subject; var addr = new MailboxAddress(fromName, fromEmail); message.From.Add(addr); if (email.body != null) { message.Body = new TextPart("html") { Text = email.body }; } var ms = new MemoryStream(); message.WriteTo(ms); ms.Position = 0; StreamReader sr = new StreamReader(ms); Google.Apis.Gmail.v1.Data.Message msg = new Google.Apis.Gmail.v1.Data.Message(); string rawString = sr.ReadToEnd(); byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString); msg.Raw = System.Convert.ToBase64String(raw); var res = service.Users.Messages.Send(msg, "me").Execute(); } return View(); } else { string redirectUri = result.RedirectUri; /// Remove port from the redirect URL. /// This action is needed for http://gmailappasp.apphb.com/ application only. /// Remove it if you hosted solution not on the http://gmailappasp.apphb.com/ redirectUri = Regex.Replace(result.RedirectUri, @"(:\d{3,5})", "", RegexOptions.Multiline | RegexOptions.IgnoreCase); /// return new RedirectResult(redirectUri); } }
///<summary>Helper method that returns a ready-to-send Gmail Message</summary> private static GmailApi.Data.Message CreateGmailMsg(BasicEmailAddress emailAddress, BasicEmailMessage emailMessage) { MimeKit.MimeMessage mimeMsg = CreateMIMEMsg(emailAddress, emailMessage); using Stream stream = new MemoryStream(); mimeMsg.WriteTo(stream); stream.Position = 0; using StreamReader sr = new StreamReader(stream); GmailApi.Data.Message gMsg = new GmailApi.Data.Message(); string rawString = sr.ReadToEnd(); byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString); gMsg.Raw = System.Convert.ToBase64String(raw); //What we send to Gmail must be a Base64 File/URL safe string. We must convert our base64 to be URL safe. (replace - and _ with + and / respectively) gMsg.Raw = gMsg.Raw.Replace("+", "-"); gMsg.Raw = gMsg.Raw.Replace("/", "_"); return(gMsg); }
static void Main(string[] args) { Console.WriteLine("Press any key to send mail!"); Console.ReadKey(); //Getting AWS credentials from App.config //note: see the app.config to get a example var credentials = new EnvironmentAWSCredentials(); //Client SES instantiated var client = new AmazonSimpleEmailServiceClient(credentials, RegionEndpoint.USEast1); var mimeMessage = new MimeMessage(); //Add sender e-mail address //Note: this e-mail address must to be allowed and checked by AWS SES mimeMessage.From.Add(new MailboxAddress("Test Sender", "*****@*****.**")); //Add e-mail address destiny mimeMessage.To.Add(new MailboxAddress("Joel", "*****@*****.**")); mimeMessage.Subject = "Test"; //Getting attachment stream var fileBytes = File.ReadAllBytes(@"C:\anyfile.pdf"); var bodyBuilder = new BodyBuilder(); bodyBuilder.TextBody = "Testing the body message"; //You must to inform the mime-type of the attachment and his name bodyBuilder.Attachments.Add("AnyAttachment.pdf", fileBytes, new ContentType("application", "pdf")); mimeMessage.Body = bodyBuilder.ToMessageBody(); //Map MimeMessage to MemoryStream, that is what SenRawEmailRequest accepts var rawMessage = new MemoryStream(); mimeMessage.WriteTo(rawMessage); client.SendRawEmail(new SendRawEmailRequest(new RawMessage(rawMessage))); Console.WriteLine("Email Sended"); Console.ReadKey(); }
public static void SendVerificationEmail(string emailaddress, string validation_guid) { const string VERIFICATION_DOMAIN = "https://nzixo03fx1.execute-api.us-west-2.amazonaws.com/prod/emailvalidation?verificationstring="; //TODO: Move this to our domain name prior to launch const string FROM = "*****@*****.**"; //TODO: Change to real domain name const string SUBJECT = "Please verify your email address"; string TO = emailaddress; string mBase64EncodedGuid = Convert.ToBase64String(Encoding.UTF8.GetBytes(emailaddress + ":" + validation_guid)); var message = new MimeMessage(); message.From.Add(new MailboxAddress("GEM CARRY EMAIL VERIFICATION", FROM)); message.To.Add(new MailboxAddress("New Gamer", TO)); message.Subject = SUBJECT; var builder = new BodyBuilder(); builder.TextBody = string.Format("To activate your account, please click the following link to verifiy your email address {0}{1}", VERIFICATION_DOMAIN, mBase64EncodedGuid); builder.HtmlBody = string.Format("To activate your account, please click <a href={0}{1}> here</a> to verify your email address.",VERIFICATION_DOMAIN,mBase64EncodedGuid); message.Body = builder.ToMessageBody(); var stream = new MemoryStream(); message.WriteTo(stream); try { AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(); var request = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } }; client.SendRawEmail(request); #if DEBUG logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Generating Validation Email for {0}.", emailaddress)); #endif // DEBUG } catch (Exception ex) { logger.WriteLog(GameLogger.LogLevel.Error, ex.Message.ToString()); } }
/// <summary> /// Splits the specified message into multiple messages. /// </summary> /// <remarks> /// Splits the specified message into multiple messages, each with a /// message/partial body no larger than the max size specified. /// </remarks> /// <returns>An enumeration of partial messages.</returns> /// <param name="message">The message.</param> /// <param name="maxSize">The maximum size for each message body.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="message"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="maxSize"/> is less than <c>1</c>. /// </exception> public static IEnumerable <MimeMessage> Split(MimeMessage message, int maxSize) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (maxSize < 1) { throw new ArgumentOutOfRangeException(nameof(maxSize)); } var options = FormatOptions.Default.Clone(); foreach (HeaderId id in Enum.GetValues(typeof(HeaderId))) { switch (id) { case HeaderId.Subject: case HeaderId.MessageId: case HeaderId.Encrypted: case HeaderId.MimeVersion: case HeaderId.ContentAlternative: case HeaderId.ContentBase: case HeaderId.ContentClass: case HeaderId.ContentDescription: case HeaderId.ContentDisposition: case HeaderId.ContentDuration: case HeaderId.ContentFeatures: case HeaderId.ContentId: case HeaderId.ContentIdentifier: case HeaderId.ContentLanguage: case HeaderId.ContentLength: case HeaderId.ContentLocation: case HeaderId.ContentMd5: case HeaderId.ContentReturn: case HeaderId.ContentTransferEncoding: case HeaderId.ContentTranslationType: case HeaderId.ContentType: break; default: options.HiddenHeaders.Add(id); break; } } var memory = new MemoryStream(); message.WriteTo(options, memory); memory.Seek(0, SeekOrigin.Begin); if (memory.Length <= maxSize) { memory.Dispose(); yield return(message); yield break; } var streams = new List <Stream> (); #if !NETSTANDARD1_3 && !NETSTANDARD1_6 var buf = memory.GetBuffer(); #else var buf = memory.ToArray(); #endif long startIndex = 0; while (startIndex < memory.Length) { // Preferably, we'd split on whole-lines if we can, // but if that's not possible, split on max size long endIndex = Math.Min(memory.Length, startIndex + maxSize); if (endIndex < memory.Length) { long ebx = endIndex; while (ebx > (startIndex + 1) && buf[ebx] != (byte)'\n') { ebx--; } if (buf[ebx] == (byte)'\n') { endIndex = ebx + 1; } } streams.Add(new BoundStream(memory, startIndex, endIndex, true)); startIndex = endIndex; } var msgid = message.MessageId ?? MimeUtils.GenerateMessageId(); int number = 1; foreach (var stream in streams) { var part = new MessagePartial(msgid, number++, streams.Count) { Content = new MimeContent(stream) }; var submessage = CloneMessage(message); submessage.MessageId = MimeUtils.GenerateMessageId(); submessage.Body = part; yield return(submessage); } yield break; }
/// <summary> /// Split the specified message into multiple messages, each with a /// message/partial body no larger than the max size specified. /// </summary> /// <param name="message">The message.</param> /// <param name="maxSize">The maximum size for each message body.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="message"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="maxSize"/> is less than <c>1</c>. /// </exception> public static IEnumerable<MimeMessage> Split(MimeMessage message, int maxSize) { if (message == null) throw new ArgumentNullException ("message"); if (maxSize < 1) throw new ArgumentOutOfRangeException ("maxSize"); using (var memory = new MemoryStream ()) { message.WriteTo (memory); memory.Seek (0, SeekOrigin.Begin); if (memory.Length <= maxSize) { yield return message; yield break; } var streams = new List<Stream> (); var buf = memory.GetBuffer (); long startIndex = 0; while (startIndex < memory.Length) { // Preferably, we'd split on whole-lines if we can, // but if that's not possible, split on max size long endIndex = Math.Min (memory.Length, startIndex + maxSize); if (endIndex < memory.Length) { long ebx = endIndex; while (ebx > (startIndex + 1) && buf[ebx] != (byte) '\n') ebx--; if (buf[ebx] == (byte) '\n') endIndex = ebx + 1; } streams.Add (new BoundStream (memory, startIndex, endIndex, true)); startIndex = endIndex; } var id = message.MessageId ?? MimeUtils.GenerateMessageId (); int number = 1; foreach (var stream in streams) { var part = new MessagePartial (id, number++, streams.Count); part.ContentObject = new ContentObject (stream, ContentEncoding.Default); var submessage = CloneMessage (message); submessage.MessageId = MimeUtils.GenerateMessageId (); submessage.Body = part; yield return submessage; } } yield break; }
void Data(MimeMessage message, CancellationToken cancellationToken) { var response = SendCommand ("DATA", cancellationToken); if (response.StatusCode != SmtpStatusCode.StartMailInput) throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response); var options = FormatOptions.Default.Clone (); options.NewLineFormat = NewLineFormat.Dos; options.HiddenHeaders.Add (HeaderId.ContentLength); options.HiddenHeaders.Add (HeaderId.ResentBcc); options.HiddenHeaders.Add (HeaderId.Bcc); using (var filtered = new FilteredStream (stream)) { filtered.Add (new SmtpDataFilter ()); message.WriteTo (options, filtered, cancellationToken); filtered.Flush (); } stream.Write (EndData, 0, EndData.Length); response = ReadResponse (cancellationToken); switch (response.StatusCode) { default: throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response); case SmtpStatusCode.AuthenticationRequired: throw new UnauthorizedAccessException (response.Response); case SmtpStatusCode.Ok: break; } }
/// <summary> /// Splits the specified message into multiple messages. /// </summary> /// <remarks> /// Splits the specified message into multiple messages, each with a /// message/partial body no larger than the max size specified. /// </remarks> /// <returns>An enumeration of partial messages.</returns> /// <param name="message">The message.</param> /// <param name="maxSize">The maximum size for each message body.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="message"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="maxSize"/> is less than <c>1</c>. /// </exception> public static IEnumerable <MimeMessage> Split(MimeMessage message, int maxSize) { if (message == null) { throw new ArgumentNullException("message"); } if (maxSize < 1) { throw new ArgumentOutOfRangeException("maxSize"); } using (var memory = new MemoryStream()) { message.WriteTo(memory); memory.Seek(0, SeekOrigin.Begin); if (memory.Length <= maxSize) { yield return(message); yield break; } var streams = new List <Stream> (); #if PORTABLE var buf = memory.ToArray(); #else var buf = memory.GetBuffer(); #endif long startIndex = 0; while (startIndex < memory.Length) { // Preferably, we'd split on whole-lines if we can, // but if that's not possible, split on max size long endIndex = Math.Min(memory.Length, startIndex + maxSize); if (endIndex < memory.Length) { long ebx = endIndex; while (ebx > (startIndex + 1) && buf[ebx] != (byte)'\n') { ebx--; } if (buf[ebx] == (byte)'\n') { endIndex = ebx + 1; } } streams.Add(new BoundStream(memory, startIndex, endIndex, true)); startIndex = endIndex; } var id = message.MessageId ?? MimeUtils.GenerateMessageId(); int number = 1; foreach (var stream in streams) { var part = new MessagePartial(id, number++, streams.Count); part.ContentObject = new ContentObject(stream, ContentEncoding.Default); var submessage = CloneMessage(message); submessage.MessageId = MimeUtils.GenerateMessageId(); submessage.Body = part; yield return(submessage); } } yield break; }
void Data (FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress) { var response = SendCommand ("DATA", cancellationToken); if (response.StatusCode != SmtpStatusCode.StartMailInput) throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response); if (progress != null) { var ctx = new SendContext (progress, null); using (var stream = new ProgressStream (Stream, ctx.Update)) { using (var filtered = new FilteredStream (stream)) { filtered.Add (new SmtpDataFilter ()); message.WriteTo (options, filtered, cancellationToken); filtered.Flush (); } } } else { using (var filtered = new FilteredStream (Stream)) { filtered.Add (new SmtpDataFilter ()); message.WriteTo (options, filtered, cancellationToken); filtered.Flush (); } } Stream.Write (EndData, 0, EndData.Length, cancellationToken); Stream.Flush (cancellationToken); response = Stream.ReadResponse (cancellationToken); switch (response.StatusCode) { default: throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response); case SmtpStatusCode.AuthenticationRequired: throw new ServiceNotAuthenticatedException (response.Response); case SmtpStatusCode.Ok: OnMessageSent (new MessageSentEventArgs (message, response.Response)); break; } }
void Bdat (FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress) { long size; using (var measure = new MeasuringStream ()) { message.WriteTo (options, measure, cancellationToken); size = measure.Length; } var bytes = Encoding.UTF8.GetBytes (string.Format ("BDAT {0} LAST\r\n", size)); Stream.Write (bytes, 0, bytes.Length, cancellationToken); if (progress != null) { var ctx = new SendContext (progress, size); using (var stream = new ProgressStream (Stream, ctx.Update)) { message.WriteTo (options, stream, cancellationToken); stream.Flush (cancellationToken); } } else { message.WriteTo (options, Stream, cancellationToken); Stream.Flush (cancellationToken); } var response = Stream.ReadResponse (cancellationToken); switch (response.StatusCode) { default: throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response); case SmtpStatusCode.AuthenticationRequired: throw new ServiceNotAuthenticatedException (response.Response); case SmtpStatusCode.Ok: OnMessageSent (new MessageSentEventArgs (message, response.Response)); break; } }