検索
ホームページJava&#&チュートリアルJava を使用して電子メールを送信する (Javamail API、Simple Java Mail、または SuprSend Java SDK)

方法 1: 電子メール通知に JavaMail API を使用する

概要:

JavaMail API は、Java クライアント アプリケーションが包括的な電子メールおよびメッセージング機能を実行できるように設計された、プラットフォームやプロトコルに依存しない堅牢なフレームワークです。この API は、トランザクション電子メール システムで作成されたさまざまなオブジェクトを表す抽象クラスを備えた汎用インターフェイスを提供します。これは、信頼性と広範な機能が最重要であるエンタープライズレベルのアプリケーションに特に役立ちます。

長所:

  1. よく構造化され、広く採用されている:

    • JavaMail API は、その堅牢な構造と、特にエンタープライズ環境で広く使用されていることで知られています。
  2. 多彩な機能:

    • 電子メールの読み取り、作成、送信など、広範な機能セットを提供します。
  3. プログラムによる統合:

    • 他のプログラムとの統合が簡素化され、プログラムによる確認やその他のメッセージの送信が容易になります。

短所:

  1. 延長コンパイル時間:

    • API の複雑さにより、開発者はコードのコンパイルに時間がかかる可能性があります。
  2. メモリ消費量:

    • JavaMail API を使用すると、Java ヒープ領域が大量に消費される可能性があります。

実装手順:

ステップ 1: JavaMail API のインストール

  • JAR ファイル (mail.jar および activity.jar) を CLASSPATH に含めます。
  • 電子メール送信用に SMTP サーバー (Pepipost など) を設定します。

ステップ 2: メールセッションのセットアップ

  • javax.mail.Session を使用して、ホスト情報を含むセッション オブジェクトを作成します。
Properties properties = new Properties(); 
Session session = Session.getDefaultInstance(properties, null);
  • 別の方法:
Properties properties = new Properties(); 
Session session = Session.getInstance(properties, null);
  • ネットワーク認証:
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("sender@gmail.com", "password");
  }
});

ステップ 3: 電子メールを作成する

  • javax.mail.internet.MimeMessage サブクラスを使用して、送信者、受信者、件名、メッセージ本文を設定します。
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("This is the email subject");
message.setText("This is the email body");

ステップ 4: 添付ファイルの追加

  • 添付ファイルを含めるには、Multipart オブジェクトを作成し、添付ファイルごとに BodyPart を追加します。
Multipart multipart = new MimeMultipart();

BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is the email body");
multipart.addBodyPart(messageBodyPart);

messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("path/to/attachment.txt");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("attachment.txt");
multipart.addBodyPart(messageBodyPart);

message.setContent(multipart);

ステップ 5: 電子メールを送信する

  • javax.mail.Transport クラスを使用して電子メールを送信します。
Transport.send(message);

完全なコード例:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail {
    public static void main(String[] args) {
      String to = "receiver@gmail.com";
      String from = "sender@gmail.com";
      String host = "smtp.gmail.com";

      Properties properties = System.getProperties();
      properties.put("mail.smtp.host", host);
      properties.put("mail.smtp.port", "465");
      properties.put("mail.smtp.ssl.enable", "true");
      properties.put("mail.smtp.auth", "true");

      Session session = Session.getInstance(properties, new javax.mail.Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication("sender@gmail.com", "password");
        }
      });

      try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Your email subject goes here");

        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("You have a new message");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource("path/to/attachment.txt");
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("attachment.txt");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        Transport.send(message);
      } catch (MessagingException mex) {
        mex.printStackTrace();
      }
   }
}

方法 2: 電子メール通知に単純な Java メールを使用する

概要:

Simple Java Mail は、Java で SMTP 電子メールを送信するプロセスを簡素化するように設計された、使いやすいメール ライブラリです。これは JavaMail API のラッパーとして機能し、基礎となる API の複雑さを軽減することで電子メール送信プロセスを合理化します。

長所:

  1. 堅牢かつ軽量:

    • Simple Java Mail は、134kB の軽量なフットプリントを維持しながら堅牢です。
  2. RFC 準拠:

    • 関連するすべての RFC に準拠しており、さまざまな電子メール クライアントとの互換性が保証されています。
  3. 認証済み SOCKS プロキシのサポート:

    • 認証された SOCKS プロキシを介した電子メールの送信をサポートします。
  4. 高度な機能:

    • HTML コンテンツ、画像、添付ファイルのサポートを提供し、複数の受信者に同時に電子メールを送信できます。

短所:

  1. 限定的なコミュニティサポート:
    • Simple Java Mail のコミュニティ サポートは、JavaMail API に比べて小規模です。

実装手順:

ステップ 1: HTML と添付ファイルを含む電子メール オブジェクトの作成

Email email = EmailBuilder.startingBlank()
    .from("From", "from@example.com")
    .to("1st Receiver", "rec1@example.com")
    .to("2nd Receiver", "rec2@example.com")
    .withSubject("Enhanced Email with HTML and Attachments")
    .withHTMLText("<h1 id="Hello">Hello!</h1><p>This is an enhanced email with HTML content.</p>")
    .withAttachment("path/to/attachment.txt")
    .buildEmail();

ステップ 2: MailerBuilder を使用してメーラー オブジェクトを作成する

Mailer mailer = MailerBuilder
    .withSMTPServer("smtp.mailtrap.io", 2525, "username", "password")
    .withTransportStrategy(TransportStrategy.SMTPS)
    .buildMailer();

ステップ 3: 拡張電子メールの送信

mailer.sendMail(email);

完全なコード例:

import org.simplejavamail.api.email.Email;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.MailerBuilder;
import org.simplejavamail.api.mailer.config.TransportStrategy;

public class SendEnhancedMail {
    public static void main(String[] args) {
        Email email = EmailBuilder.startingBlank()
            .from("From", "from@example.com")
            .to("1st Receiver", "case1@example.com")
            .to("2nd Receiver", "case2@example.com")
            .withSubject("Enhanced Email with HTML and Attachments")
            .withHTMLText("<h1 id="Hello">Hello!</h1><p>This is an enhanced email with HTML content.</p>")
            .withAttachment("path/to/attachment.txt")
            .buildEmail();

        Mailer mailer = MailerBuilder
            .withSMTPServer("smtp.mailtrap.io", 2525, "username", "password")
            .withTransportStrategy(TransportStrategy.SMTPS)
            .buildMailer();

        mailer.sendMail(email);
    }
}

方法 3: JAVA SDK でマルチチャネル通知に SuprSend を使用する

概要:

SuprSend は、統合 API を介した電子メール、SMS、プッシュ通知などのさまざまなチャネルにわたる通知の送信をサポートする、包括的なサードパーティのマルチチャネル通知インフラストラクチャを提供します。 SuprSend を活用することで、開発者は複雑な通知ワークフローをシームレスに管理できます。

主な機能と利点:

  1. 広範な統合オプション:

    • 50 を超える通信サービス プロバイダー (CSP) とシームレスに統合し、Mixpanel、Segment、Twilio、Mailchimp、Slack、Teams、SNS、Vonage、Whatsapp などを含む複数のチャネルをサポートします。
  2. 技術依存なし:

    • Manages the entire notification lifecycle without heavy reliance on the engineering team. Integrate the JAVA SDK once, and the product team can handle the rest.
  3. Intelligent Routing:

    • Implements intelligent cross-channel flows across providers without requiring technical dependencies.
  4. In-App SDK:

    • Provides a developer-ready in-app layer for both web and mobile applications.
  5. Granular Template Management:

    • Features an intuitive drag & drop editor for designing templates, offering superior control over content.
  6. Powerful Workspace:

    • Manages multiple projects with distinct integrations, workflows, and templates within each workspace.
  7. Unified Analytics:

    • Provides a unified view of cross-channel analytics, enabling data-driven decision-making.
  8. Smart Automation:

    • Automates synchronization, refreshing, and notification triggers to streamline operations.
  9. Scalability:

    • Automates scalability, ensuring a hassle-free experience.

Cons:

  1. Cost Considerations:
    • Managing multiple notification channels may incur costs.
  2. *Monthly Notification Limit:*
    • Though SuprSend provides 10k notifications free every month, which resets every month, you can also buy credits.

Limits:**

  • There may be restrictions on the number of notifications per month.

Implementation Steps:

Step 1: Integrating the JAVA SDK

  1. Install the SuprSend JAVA SDK:
    • Add the SDK to your JAVA project via Maven or Gradle.

Step 2: Configuring the API Key and Workspace Secret

  1. Set Up Configuration:
    • Obtain the API key and workspace secret from your SuprSend account and configure them in your JAVA project.

Step 3: Creating and Sending Notifications

  1. Send Notifications via JAVA SDK:
    • Use the SDK to send notifications, specifying the required channel (email, SMS, push, etc.) and the content.
import com.suprsend.Notification;
import com.suprsend.NotificationBuilder;
import com.suprsend.SuprSendClient;

public class SendNotification {
    public static void main(String[] args) {
        // Initialize the SuprSendClient with API key and Workspace Secret
        SuprSendClient client = new SuprSendClient("your_api_key", "your_workspace_secret");

        // Build the notification
        Notification notification = NotificationBuilder.startingBlank()
            .withRecipientEmail("recipient@example.com")
            .withRecipientSMS("recipient_phone_number")
            .withSubject("Notification Subject")
            .withHTMLBody("<h1 id="Hello">Hello!</h1><p>This is a multichannel notification.</p>")
            .build();

        // Send the notification
        client.sendNotification(notification);
    }
}

Complete Code Example with JAVA SDK:

import com.suprsend.Notification;
import com.suprsend.NotificationBuilder;
import com.suprsend.SuprSendClient;

public class SuprSendExample {
    public static void main(String[] args) {
        // Initialize the SuprSendClient with API key and Workspace Secret
        SuprSendClient client = new SuprSendClient("your_api_key", "your_workspace_secret");

        // Create the notification
        Notification notification = NotificationBuilder.startingBlank()
            .withRecipientEmail("receiver@example.com")
            .withSubject("Subject of the Notification")
            .withHTMLBody("<h1 id="Hello">Hello!</h1><p>This is a notification from SuprSend.</p>")
            .withAttachment("path/to/attachment.txt")
            .build();

        // Send the notification
        client.sendNotification(notification);
    }
}

These methods offer a comprehensive guide to sending email notifications using Java, with varying levels of complexity and integration capabilities to suit different needs and scenarios.


You may want to check out other SuprSend SDKs too. Consider giving us a star after usage. It's free and open.

Send emails using Java (Javamail API or Simple Java Mail or SuprSend Java SDK) suprsend / suprsend-go

SuprSend SDK for go

suprsend-go

SuprSend Go SDK

Installation

go get github.com/suprsend/suprsend-go
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

import (
    "log"

    suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    opts := []suprsend.ClientOption{
        // suprsend.WithDebug(true),
    }
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__", opts...)
    if err != nil {
        log.Println(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Trigger Workflow

package main
import (
    "log"

    suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    // Instantiate Client
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__")
    if err != nil {
        log.Println(err)
        return
    }
    // Create workflow body
    wfBody := map[string]interface{}{
        "name":                  "Workflow Name",
        "template":              "template slug",
        "notification_category": "category",
        // "delay":                 "15m", // Chek duration format in documentation
        "users": []map[string]interface{}{
            {
                "distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
                
Enter fullscreen mode Exit fullscreen mode
View on GitHub

Send emails using Java (Javamail API or Simple Java Mail or SuprSend Java SDK) suprsend / suprsend-py-sdk

SuprSend SDK for python3

suprsend-py-sdk

This package can be included in a python3 project to easily integrate with SuprSend platform.

We're working towards creating SDK in other languages as well.

SuprSend SDKs available in following languages

  • python3 >= 3.7 (suprsend-py-sdk)
  • node (suprsend-node-sdk)
  • java (suprsend-java-sdk)

Installation

suprsend-py-sdk is available on PyPI. You can install using pip.

pip install suprsend-py-sdk
Enter fullscreen mode Exit fullscreen mode

This SDK depends on a system package called libmagic. You can install it as follows:

<span class="pl-c"># On debian based systems</span>
sudo apt install libmagic

<span class="pl-c"># If you are using macOS</span>
brew install libmagic
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

from suprsend import Suprsend
# Initialize SDK
supr_client = Suprsend("workspace_key", "workspace_secret")
Enter fullscreen mode Exit fullscreen mode

Following example shows a sample request for triggering a workflow. It triggers a notification to a user with id: distinct_id, email: user@example.com & androidpush(fcm-token): __android_push_fcm_token__ using template purchase-made and notification_category system

from suprsend import Workflow
Enter fullscreen mode Exit fullscreen mode
View on GitHub

Send emails using Java (Javamail API or Simple Java Mail or SuprSend Java SDK) suprsend / suprsend-node-sdk

Official SuprSend SDK for Node.js

suprsend-node-sdk

This package can be included in a node project to easily integrate with SuprSend platform.

Installation

npm install @suprsend/node-sdk@latest
Enter fullscreen mode Exit fullscreen mode

Initialization

const { Suprsend } = require("@suprsend/node-sdk");

const supr_client = new Suprsend("workspace_key", "workspace_secret");
Enter fullscreen mode Exit fullscreen mode

Trigger workflow from API

It is a unified API to trigger workflow and doesn't require user creation before hand. If you are using our frontend SDK's to configure notifications and passing events and user properties from third-party data platforms like Segment, then event-based trigger would be a better choice.

const { Suprsend, WorkflowTriggerRequest } = require("@suprsend/node-sdk");
const supr_client = new Suprsend("workspace_key", "workspace_secret");

// workflow payload
const body = {
  workflow: "_workflow_slug_",
  actor: {
    distinct_id: "0fxxx8f74-xxxx-41c5-8752-xxxcb6911fb08",
    name: "actor_1",
  },
  recipients: [
    {
      distinct_id: "0gxxx9f14-xxxx-23c5-1902-xxxcb6912ab09",
      $email: ["abc@example.com"
Enter fullscreen mode Exit fullscreen mode
View on GitHub

Send emails using Java (Javamail API or Simple Java Mail or SuprSend Java SDK) suprsend / suprsend-react-inbox

SuprSend SDK for integrating inbox functionality in React applications

@suprsend/react-inbox

Integrating SuprSend Inbox channel in React websites can be done in two ways:

  • SuprSendInbox component which comes with UI and customizing props.
  • SuprSendProvider headless component and hooks, incase you want to totally take control of UI. (example: Full page notifications).

Detailed documentation can be found here: https://docs.suprsend.com/docs/inbox-react

Installation

You can install SuprSend inbox SDK using npm/yarn

npm install @suprsend/react-inbox
Enter fullscreen mode Exit fullscreen mode

SuprSendInbox Integration

After installing, Import the component in your code and use it as given below. Replace the variables with actual values.

import SuprSendInbox from '@suprsend/react-inbox'
import 'react-toastify/dist/ReactToastify.css' // needed for toast notifications, can be ignored if hideToast=true

// add to your react component;
<suprsendinbox workspacekey="<workspace_key>" subscriberid="<subscriber_id>" distinctid="<distinct_id>"></suprsendinbox>
Enter fullscreen mode Exit fullscreen mode
interface ISuprSendInbox {
  workspaceKey: string
  distinctId: string | null
  subscriberId: string | null
  tenantId?: string
  stores?: IStore[]
  pageSize?: number
  pagination?: boolean
Enter fullscreen mode Exit fullscreen mode
View on GitHub

以上がJava を使用して電子メールを送信する (Javamail API、Simple Java Mail、または SuprSend Java SDK)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
2025年のトップ4 JavaScriptフレームワーク:React、Angular、Vue、Svelte2025年のトップ4 JavaScriptフレームワーク:React、Angular、Vue、SvelteMar 07, 2025 pm 06:09 PM

この記事では、2025年の上位4つのJavaScriptフレームワーク(React、Angular、Vue、Svelte)を分析し、パフォーマンス、スケーラビリティ、将来の見通しを比較します。 強力なコミュニティと生態系のためにすべてが支配的なままですが、彼らの相対的なポップ

カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?Mar 17, 2025 pm 05:44 PM

この記事では、カフェインとグアバキャッシュを使用してJavaでマルチレベルキャッシュを実装してアプリケーションのパフォーマンスを向上させています。セットアップ、統合、パフォーマンスの利点をカバーし、構成と立ち退きポリシー管理Best Pra

node.js 20:キーパフォーマンスが向上し、新機能node.js 20:キーパフォーマンスが向上し、新機能Mar 07, 2025 pm 06:12 PM

node.js 20は、V8エンジンの改善、特により速いガベージコレクションとI/Oを介してパフォーマンスを大幅に向上させます。 新機能には、より良いWebセンブリのサポートと洗練されたデバッグツール、開発者の生産性とアプリケーション速度の向上が含まれます。

Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Mar 17, 2025 pm 05:35 PM

Javaのクラスロードには、ブートストラップ、拡張機能、およびアプリケーションクラスローダーを備えた階層システムを使用して、クラスの読み込み、リンク、および初期化が含まれます。親の委任モデルは、コアクラスが最初にロードされ、カスタムクラスのLOAに影響を与えることを保証します

Iceberg:データレイクテーブルの未来Iceberg:データレイクテーブルの未来Mar 07, 2025 pm 06:31 PM

大規模な分析データセットのオープンテーブル形式であるIcebergは、データの湖のパフォーマンスとスケーラビリティを向上させます。 内部メタデータ管理を通じて、寄木細工/ORCの制限に対処し、効率的なスキーマの進化、タイムトラベル、同時wを可能にします

Spring Boot Snakeyaml 2.0 CVE-2022-1471問題修正Spring Boot Snakeyaml 2.0 CVE-2022-1471問題修正Mar 07, 2025 pm 05:52 PM

この記事では、リモートコードの実行を可能にする重大な欠陥であるSnakeyamlのCVE-2022-1471の脆弱性について説明します。 Snakeyaml 1.33以降のSpring Bootアプリケーションをアップグレードする方法は、このリスクを軽減する方法を詳述し、その依存関係のアップデートを強調しています

Javaで機能的なプログラミング技術を実装するにはどうすればよいですか?Javaで機能的なプログラミング技術を実装するにはどうすればよいですか?Mar 11, 2025 pm 05:51 PM

この記事では、Lambda式、Streams API、メソッド参照、およびオプションを使用して、機能プログラミングをJavaに統合することを調べます。 それは、簡潔さと不変性を通じてコードの読みやすさと保守性の改善などの利点を強調しています

高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?Mar 17, 2025 pm 05:46 PM

この記事では、Javaプロジェクト管理、自動化の構築、依存関係の解像度にMavenとGradleを使用して、アプローチと最適化戦略を比較して説明します。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール