搜尋
首頁Javajava教程使用 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

  • 在 CLASSPATH 中包含 JAR 檔案(mail.jar 和activation.jar)。
  • 設定 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 Mail 進行電子郵件通知

概述:

Simple Java Mail 是一個使用者友善的郵件庫,旨在簡化用 Java 發送 SMTP 電子郵件的過程。它可作為 JavaMail API 的包裝器,透過降低底層 API 的複雜性來簡化電子郵件發送流程。

優點:

  1. 堅固且輕量:

    • Simple Java Mail 非常強大,同時保持 134kB 的輕量級佔用空間。
  2. RFC 合規性:

    • 它符合所有相關的 RFC,確保與各種電子郵件用戶端的相容性。
  3. 經過驗證的 SOCKS 代理支援:

    • 支援透過經過驗證的 SOCKS 代理程式發送電子郵件。
  4. 進階功能:

    • 提供對 HTML 內容、圖像和附件的支持,並允許同時向多個收件者發送電子郵件。

缺點:

  1. 有限的社區支持:
    • 與 JavaMail API 相比,Simple Java Mail 的社群支援較小。

實施步驟:

第 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 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 跨電子郵件、簡訊和推播通知等各種管道發送通知。透過利用 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用Java和JavaCV提升視頻質量?為什麼效果有限?如何使用Java和JavaCV提升視頻質量?為什麼效果有限?Apr 19, 2025 pm 03:57 PM

問題介紹:視頻質量提升是視頻處理中的一個重要環節,尤其是在處理低清晰度的視頻時,如何利用Java語言和�...

如何讓SpringBoot中的@RequestBody註解正確接收非JSON格式的字符串參數?如何讓SpringBoot中的@RequestBody註解正確接收非JSON格式的字符串參數?Apr 19, 2025 pm 03:54 PM

在處理SpringBoot應用中,我們經常會遇到如何正確接收請求參數的問題。特別是當參數格式不是常見的JSON時,更�...

在 Java 中聲明 ConcurrentHashMap 時,添加 static 關鍵字會帶來什麼影響?在 Java 中聲明 ConcurrentHashMap 時,添加 static 關鍵字會帶來什麼影響?Apr 19, 2025 pm 03:51 PM

Java中聲明ConcurrentHashMap時加static的影響在Java編程中,ConcurrentHashMap...

我在配置自定義線程池時沒有配置initialize()方法,為什麼程序仍然可以正常運行?我在配置自定義線程池時沒有配置initialize()方法,為什麼程序仍然可以正常運行?Apr 19, 2025 pm 03:48 PM

自定義線程池中的initialize()方法的作用詳解當你在配置自定義線程池時,可能會注意到有一個initialize()方法。很...

曲線積分換元:為什麼用y=sin(t)替換而非極坐標變換?曲線積分換元:為什麼用y=sin(t)替換而非極坐標變換?Apr 19, 2025 pm 03:45 PM

關於曲線積分中變量代換的疑問提問者遇到一個曲線積分問題,其中一個步驟的計算結果令其困惑。題目給出了...

Java中'類::實例方法”方法引用如何正確理解和應用?Java中'類::實例方法”方法引用如何正確理解和應用?Apr 19, 2025 pm 03:39 PM

Java方法引用“類::實例方法”的疑惑解答在Java編程中,方法引用是一種簡潔而強大的功能,它允許開發者通過�...

Spring Boot異步任務中,子線程如何訪問主線程的Request信息?Spring Boot異步任務中,子線程如何訪問主線程的Request信息?Apr 19, 2025 pm 03:36 PM

SpringBoot項目中子線程無法訪問主線程Request信息的問題及解決方案在Spring...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中