搜索
首页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
JVM中的类加载程序子系统如何促进平台独立性?JVM中的类加载程序子系统如何促进平台独立性?Apr 23, 2025 am 12:14 AM

类加载器通过统一的类文件格式、动态加载、双亲委派模型和平台无关的字节码,确保Java程序在不同平台上的一致性和兼容性,实现平台独立性。

Java编译器会产生特定于平台的代码吗?解释。Java编译器会产生特定于平台的代码吗?解释。Apr 23, 2025 am 12:09 AM

Java编译器生成的代码是平台无关的,但最终执行的代码是平台特定的。1.Java源代码编译成平台无关的字节码。2.JVM将字节码转换为特定平台的机器码,确保跨平台运行但性能可能不同。

JVM如何处理不同操作系统的多线程?JVM如何处理不同操作系统的多线程?Apr 23, 2025 am 12:07 AM

多线程在现代编程中重要,因为它能提高程序的响应性和资源利用率,并处理复杂的并发任务。JVM通过线程映射、调度机制和同步锁机制,在不同操作系统上确保多线程的一致性和高效性。

在Java的背景下,'平台独立性”意味着什么?在Java的背景下,'平台独立性”意味着什么?Apr 23, 2025 am 12:05 AM

Java的平台独立性是指编写的代码可以在任何安装了JVM的平台上运行,无需修改。1)Java源代码编译成字节码,2)字节码由JVM解释执行,3)JVM提供内存管理和垃圾回收功能,确保程序在不同操作系统上运行。

Java应用程序仍然可以遇到平台特定的错误或问题吗?Java应用程序仍然可以遇到平台特定的错误或问题吗?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

云计算如何影响Java平台独立性的重要性?云计算如何影响Java平台独立性的重要性?Apr 22, 2025 pm 07:05 PM

云计算显着提升了Java的平台独立性。 1)Java代码编译为字节码,由JVM在不同操作系统上执行,确保跨平台运行。 2)使用Docker和Kubernetes部署Java应用,提高可移植性和可扩展性。

Java的平台独立性在广泛采用中扮演着什么角色?Java的平台独立性在广泛采用中扮演着什么角色?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

容器化技术(例如Docker)如何影响Java平台独立性的重要性?容器化技术(例如Docker)如何影响Java平台独立性的重要性?Apr 22, 2025 pm 06:49 PM

容器化技术如Docker增强而非替代Java的平台独立性。1)确保跨环境的一致性,2)管理依赖性,包括特定JVM版本,3)简化部署过程,使Java应用更具适应性和易管理性。

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脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),