Heim > Java > javaLernprogramm > Hauptteil

Senden Sie E-Mails mit Java (Javamail API oder Simple Java Mail oder SuprSend Java SDK)

王林
Freigeben: 2024-08-05 16:52:40
Original
766 Leute haben es durchsucht

Methode 1: Verwendung der JavaMail-API für E-Mail-Benachrichtigungen

Überblick:

Die JavaMail-API ist ein robustes, plattform- und protokollunabhängiges Framework, das Java-Clientanwendungen bei der Ausführung umfassender E-Mail- und Messaging-Funktionen unterstützt. Diese API bietet eine generische Schnittstelle mit abstrakten Klassen, die verschiedene Objekte darstellen, die in transaktionalen E-Mail-Systemen erstellt werden. Es ist besonders nützlich für Anwendungen auf Unternehmensebene, bei denen Zuverlässigkeit und umfangreiche Funktionalitäten von größter Bedeutung sind.

Vorteile:

  1. Gut strukturiert und weit verbreitet:

    • JavaMail API ist bekannt für seine solide Struktur und weit verbreitete Verwendung, insbesondere in Unternehmensumgebungen.
  2. Vielseitige Funktionalität:

    • Es bietet umfangreiche Funktionen, darunter Lesen, Verfassen und Senden von E-Mails.
  3. Programmatische Integration:

    • Vereinfacht die Integration mit anderen Programmen und erleichtert das programmgesteuerte Senden von Bestätigungen und anderen Nachrichten.

Nachteile:

  1. Verlängerte Kompilierungszeit:

    • Entwickler müssen aufgrund der Komplexität der API möglicherweise mit längeren Codekompilierungszeiten rechnen.
  2. Speicherverbrauch:

    • Die Verwendung der JavaMail-API kann zu einem erheblichen Verbrauch von Java-Heap-Speicherplatz führen.

Implementierungsschritte:

Schritt 1: JavaMail-API installieren

  • Fügen Sie JAR-Dateien (mail.jar und activate.jar) in den CLASSPATH ein.
  • Konfigurieren Sie einen SMTP-Server (z. B. Pepipost) für die E-Mail-Übertragung.

Schritt 2: Einrichten der Mail-Sitzung

  • Erstellen Sie mit javax.mail.Session ein Sitzungsobjekt mit Hostinformationen.
Properties properties = new Properties(); 
Session session = Session.getDefaultInstance(properties, null);
Nach dem Login kopieren
  • Alternativ:
Properties properties = new Properties(); 
Session session = Session.getInstance(properties, null);
Nach dem Login kopieren
  • Netzwerkauthentifizierung:
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("sender@gmail.com", "password");
  }
});
Nach dem Login kopieren

Schritt 3: Verfassen der E-Mail

  • Verwenden Sie die Unterklasse javax.mail.internet.MimeMessage, um den Absender, den Empfänger, den Betreff und den Nachrichtentext festzulegen.
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");
Nach dem Login kopieren

Schritt 4: Anhänge hinzufügen

  • Um Anhänge einzuschließen, erstellen Sie ein Multipart-Objekt und fügen Sie für jeden Anhang ein BodyPart hinzu.
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);
Nach dem Login kopieren

Schritt 5: Senden der E-Mail

  • Verwenden Sie die Klasse javax.mail.Transport, um die E-Mail zu senden.
Transport.send(message);
Nach dem Login kopieren

Vollständiges Codebeispiel:

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();
      }
   }
}
Nach dem Login kopieren

Methode 2: Einfaches Java Mail für E-Mail-Benachrichtigungen verwenden

Überblick:

Simple Java Mail ist eine benutzerfreundliche Mailing-Bibliothek, die den Prozess des Sendens von SMTP-E-Mails in Java vereinfachen soll. Es dient als Wrapper für die JavaMail-API und optimiert den E-Mail-Versandprozess durch Reduzierung der Komplexität der zugrunde liegenden API.

Vorteile:

  1. Robust und leicht:

    • Simple Java Mail ist robust und behält gleichzeitig einen geringen Platzbedarf von 134 KB bei.
  2. RFC-Konformität:

    • Es entspricht allen relevanten RFCs und gewährleistet so die Kompatibilität mit verschiedenen E-Mail-Clients.
  3. Authentifizierte SOCKS-Proxy-Unterstützung:

    • Unterstützt das Senden von E-Mails über einen authentifizierten SOCKS-Proxy.
  4. Erweiterte Funktionen:

    • Bietet Unterstützung für HTML-Inhalte, Bilder und Anhänge und ermöglicht das gleichzeitige Senden von E-Mails an mehrere Empfänger.

Nachteile:

  1. Begrenzter Community-Support:
    • Die Community-Unterstützung für Simple Java Mail ist im Vergleich zur JavaMail-API geringer.

Implementierungsschritte:

Schritt 1: Erstellen eines E-Mail-Objekts mit HTML und Anhängen

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("<html><body><h1>Hello!</h1><p>This is an enhanced email with HTML content.</p></body></html>")
    .withAttachment("path/to/attachment.txt")
    .buildEmail();
Nach dem Login kopieren

Schritt 2: Erstellen eines Mailer-Objekts mit MailerBuilder

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

Schritt 3: Senden der erweiterten E-Mail

mailer.sendMail(email);
Nach dem Login kopieren

Vollständiges Codebeispiel:

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("<html><body><h1>Hello!</h1><p>This is an enhanced email with HTML content.</p></body></html>")
            .withAttachment("path/to/attachment.txt")
            .buildEmail();

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

        mailer.sendMail(email);
    }
}
Nach dem Login kopieren

Methode 3: Verwendung von SuprSend für Mehrkanalbenachrichtigungen mit JAVA SDKs

Überblick:

SuprSend bietet eine umfassende Multichannel-Benachrichtigungsinfrastruktur von Drittanbietern, die das Senden von Benachrichtigungen über verschiedene Kanäle wie E-Mail, SMS und Push-Benachrichtigungen über eine einheitliche API unterstützt. Durch die Nutzung von SuprSend können Entwickler komplexe Benachrichtigungsworkflows nahtlos verwalten.

Hauptmerkmale und Vorteile:

  1. Umfangreiche Integrationsoptionen:

    • Nahtlose Integration mit über 50 Kommunikationsdienstanbietern (CSPs) und Unterstützung mehrerer Kanäle, darunter Mixpanel, Segment, Twilio, Mailchimp, Slack, Teams, SNS, Vonage, WhatsApp und mehr.
  2. Keine technische Abhängigkeit:

    • 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("<html><body><h1>Hello!</h1><p>This is a multichannel notification.</p></body></html>")
            .build();

        // Send the notification
        client.sendNotification(notification);
    }
}
Nach dem Login kopieren

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("<html><body><h1>Hello!</h1><p>This is a notification from SuprSend.</p></body></html>")
            .withAttachment("path/to/attachment.txt")
            .build();

        // Send the notification
        client.sendNotification(notification);
    }
}
Nach dem Login kopieren

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
Nach dem Login kopieren
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)
    }
}
Nach dem Login kopieren
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",
                
Nach dem Login kopieren
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
Nach dem Login kopieren
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
Nach dem Login kopieren
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

from suprsend import Suprsend
# Initialize SDK
supr_client = Suprsend("workspace_key", "workspace_secret")
Nach dem Login kopieren
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
Nach dem Login kopieren
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
Nach dem Login kopieren
Enter fullscreen mode Exit fullscreen mode

Initialization

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

const supr_client = new Suprsend("workspace_key", "workspace_secret");
Nach dem Login kopieren
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"
Nach dem Login kopieren
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
Nach dem Login kopieren
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>'
/>
Nach dem Login kopieren
Enter fullscreen mode Exit fullscreen mode
interface ISuprSendInbox {
  workspaceKey: string
  distinctId: string | null
  subscriberId: string | null
  tenantId?: string
  stores?: IStore[]
  pageSize?: number
  pagination?: boolean
Nach dem Login kopieren
Enter fullscreen mode Exit fullscreen mode
View on GitHub

Das obige ist der detaillierte Inhalt vonSenden Sie E-Mails mit Java (Javamail API oder Simple Java Mail oder SuprSend Java SDK). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!