この簡単なチュートリアルでは、** C#を使用してメールでWord Documentを送信する方法を学習します。次の例では、 C#を使用して電子メール本文でWord文書を送信する**がいかに簡単であるかがわかります。この例は、Linux、macOS、Windowsなどの一般的に利用可能なオペレーティングシステムのいずれかで使用できます。
C#を使用して電子メールでWord文書を送信する手順
- VisualStudioのNuGetパッケージマネージャーツールからAspose.WordsおよびAspose.Emailライブラリをインストールします。
- Documentクラスオブジェクトを初期化して、メールとして送信するドキュメントを読み込みます
- ドキュメントをストリームとして中間MHTML形式で保存します
- MailMessageクラスインスタンスをインスタンス化して、MHTMLをMailMessageとしてロードし、そのプロパティを設定します
- SMTPクライアントをインスタンス化し、C#を使用してWord文書を電子メールとして送信します
上記の手順では、最初の手順でメールとして送信するWordドキュメントを読み込みます。次に、ロードされたドキュメントを中間のMHTML形式でストリームに保存します。以降の手順では、* MailMessageクラスを使用してMHTMLをロードし、そのメールプロパティを設定します。最後に、SMTPクライアントクラスのインスタンスがインスタンス化され、 C#でDOCXからメールを作成*します。
C#を使用して電子メールでWord文書を送信するコード
using System; | |
using System.IO; | |
using Aspose.Email; | |
using Aspose.Email.Clients; | |
using Aspose.Email.Clients.Smtp; | |
using Aspose.Words; | |
namespace WordKB | |
{ | |
class WordsEmail | |
{ | |
static void Main(string[] args) | |
{ | |
// Use Aspose.Words and Aspose.Email licenses to remove evaluation version limitations | |
Aspose.Words.License LicenseForWord = new Aspose.Words.License(); | |
LicenseForWord.SetLicense("Aspose.Total.API.lic"); | |
Aspose.Email.License LicenseForEmail = new Aspose.Email.License(); | |
LicenseForEmail.SetLicense("Aspose.Total.API.lic"); | |
// Load the document for sending as email using Document class | |
Document EmaiDocument = new Document("EmailDocument.docx"); | |
// Convert the document to MHTML format by using memory stream | |
Stream EmailStream = new MemoryStream(); | |
EmaiDocument.Save(EmailStream, SaveFormat.Mhtml); | |
// Now, reset the EmailStream position to the beginning | |
EmailStream.Position = 0; | |
// Create an Aspose.Email message from the saved stream | |
Aspose.Email.MailMessage EmailMessage = | |
Aspose.Email.MailMessage.Load(EmailStream, new MhtmlLoadOptions()); | |
// Set properties of email to send | |
EmailMessage.From = "your_from_email@email.com"; | |
EmailMessage.To = "your_to_email@email.com"; | |
EmailMessage.Subject = "Test Message using Aspose. Words and Aspose.Email APIs"; | |
// Initialize SMTP client and it's properties to send email | |
SmtpClient SMTPClient = new SmtpClient(); | |
SMTPClient.Host = "smtp.gmail.com"; | |
SMTPClient.Username = "YourEmail@gmail.com"; | |
SMTPClient.Password = "Your Gamil Password"; | |
SMTPClient.Port = 587; | |
SMTPClient.SecurityOptions = SecurityOptions.SSLExplicit; | |
// Send word email message | |
SMTPClient.Send(EmailMessage); | |
} | |
} | |
} |
上記の例では、2段階のアプローチを採用して* C#を使用して電子メール本文でWord文書を送信しています*。最初のステップでは、ストリームを使用してDOCXを中間形式のMHTMLファイルとしてロードおよび保存しました。次に、2番目のステップで、MailMessageを使用してMHTMLをストリームにロードしました。最後に、* SMTPクライアント*を使用して、ドキュメントをC#で電子メールで送信します。
この簡単なトピックでは、* C#を使用してDOCXから電子メールを作成する方法*について説明しました。ただし、DOCXからMDファイルへの変換をお探しの場合は、C#を使用してWordをMarkdownに変換する方法の記事を参照してください。