El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

SMTP Code Calling Example (Java)

Updated on 2024-12-12 GMT+08:00

This section uses Java code as an example, for example, Code Calling Sample. If the Java code does not meet the requirements, see Single Connection (Sending Multiple Times) and Example Email with an Attachment.

NOTE:

JDK 1.8 or later is recommended.

Prerequisites

You have obtained the sender address from the Email Message console.

You have obtained the SMTP account and password from the KooMessage operations personnel.

Supported SMTP Server and Port

 private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
 private static final String SMTP_PORT = "465";

Code Calling Sample

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
 
public class SampleMail {
    private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
    private static final String SMTP_PORT = "465";
 
    public static void main(String[] args) {
        // Configure the environment attributes for sending emails.
        final Properties props = new Properties();
        // Identity authentication is required for sending emails through SMTP.
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // SMTP uses SSL to ensure security. If you do not want to import the KM certificate, add downstream code.
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        // If SSL is used, delete the configuration of port 25 and perform the following configuration:
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.port", SMTP_PORT);
        // SMTP account of the sender. Replace username with the SMTP account provided by KooMessage.
        props.put("mail.user", "username");
        // Password required for accessing the SMTP service (set when selecting the sender address on the console). Replace password with the SMTP password provided by KooMessage.
        props.put("mail.password", "password");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.starttls.enable","true");
        // Construct authorization information for SMTP authentication.
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // Username and password.
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // Use the environment attributes and authorization information to create an email session.
        Session mailSession = Session.getInstance(props, authenticator);
        // mailSession.setDebug(true);
        // UUID uuid = UUID.randomUUID();
        // final String messageIDValue = "<" + uuid.toString() + ">";
        // Create an email message.
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            // Customize Message-ID.
            //setHeader("Message-ID", messageIDValue);
            //}
        };
        try {
            // Set the email address and name of the sender. Enter the sender address configured on the console, for example, test@qq.com. The value must be the same as that of mail.user. The name can be customized.
            InternetAddress from = new InternetAddress("test@qq.com", "test");
            message.setFrom(from);
            //(Optional) Set the reply address.
            //Address[] a = new Address[1];
            //a[0] = new InternetAddress("***");
            //message.setReplyTo(a);
            // Set the recipient email address, for example, yyy@yyy.com.
            InternetAddress to = new InternetAddress("xxx@xxx.com");
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            // If the email is sent to multiple recipients at the same time, replace the preceding two lines with the following (because of some restrictions of the receiving system, try to send the email to one recipient at a time. In addition, a maximum of 50 recipients are allowed at a time.):
            //InternetAddress[] adds = new InternetAddress[2];
            //adds[0] = new InternetAddress("xxx@xxx.com");
            //adds[1] = new InternetAddress("xxx@xxx.com");
            //message.setRecipients(Message.RecipientType.TO, adds);
 
            // Set the email title.
            message.setSubject("Test email");
            message.setHeader("Content-Transfer-Encoding", "base64");
            // Set the email body type: text/plain or text/html
 message.setContent("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>hello world</title>\n</head>\n<body>\n " + "<h1>My first title</h1>\n    <p>My first paragraph.</p>\n</body>\n</html>", "text/html;charset=UTF-8");
           // Send the email.
            Transport.send(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            String err = e.getMessage();
            err = new String(err.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println(err);
        }
    }
}

Single Connection (Sending Multiple Times)

If you use a single connection and send emails for multiple times, you can refer to the following example to improve the sending performance.

import jakarta.mail.Authenticator;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
 
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
 
public class SampleMail {
    private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
 
    private static final String SMTP_PORT = "465";
 
    public static void main(String[] args) {
        // Configure the environment attributes for sending emails.
        final Properties props = new Properties();
        // Identity authentication is required for sending emails through SMTP.
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // SMTP uses SSL to ensure security. If you do not want to import the KM certificate, add downstream code.
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        // If SSL is used, delete the configuration of port 25 and perform the following configuration:
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.port", SMTP_PORT);
        // SMTP account of the sender. Replace username with the SMTP account provided by KooMessage.
        props.put("mail.user", "username");
        // Password required for accessing the SMTP service (set when selecting the sender address on the console). Replace password with the SMTP password provided by KooMessage.
        props.put("mail.password", "password");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.starttls.enable","true");
        // Construct authorization information for SMTP authentication.
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // Username and password.
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // Use the environment attributes and authorization information to create an email session.
        Session mailSession = Session.getInstance(props, authenticator);
        // mailSession.setDebug(true);
        // UUID uuid = UUID.randomUUID();
        // final String messageIDValue = "<" + uuid.toString() + ">";
        // Create an email message.
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            // Customize Message-ID.
            //setHeader("Message-ID", messageIDValue);
            //}
        };
        Transport transport = null;
        try {
            // Set the email address and name of the sender. Enter the sender address configured on the console, for example, test@qq.com. The value must be the same as that of mail.user. The name can be customized.
            transport = mailSession.getTransport();
            transport.connect(props.getProperty("mail.user"), props.getProperty("mail.password"));
            List<String> toList = Arrays.asList("xxx1@xx.com", "xxx2@xx.com", "xxx3@xx.com");
            for (String to : toList) {
                InternetAddress from = new InternetAddress("jwl6C@kmemailtest.cn", "test");
                message.setFrom(from);
                //(Optional) Set the reply address.
                //Address[] a = new Address[1];
                //a[0] = new InternetAddress("***");
                //message.setReplyTo(a);
                // Set the recipient email address, for example, yyy@yyy.com.
                InternetAddress toAddress = new InternetAddress(to);
                message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
                // If the email is sent to multiple recipients at the same time, replace the preceding two lines with the following (because of some restrictions of the receiving system, try to send the email to one recipient at a time. In addition, a maximum of 50 recipients are allowed at a time.):
                //InternetAddress[] adds = new InternetAddress[2];
                //adds[0] = new InternetAddress("xxx@xxx.com");
                //adds[1] = new InternetAddress("xxx@xxx.com");
                //message.setRecipients(Message.RecipientType.TO, adds);
 
                // Set the email title.
                message.setSubject ("Test email");
                message.setHeader("Content-Transfer-Encoding", "base64");
                // Set the email body type: text/plain or text/html
                message.setContent(
                    "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>hello world</title>\n</head>\n<body>\n "
                        + "<h1>My first title</h1>\n    <p>My first paragraph.</p>\n</body>\n</html>",
                    "text/html;charset=UTF-8");
               // Send the email.
                transport.sendMessage(message, message.getAllRecipients());
            }
 
        } catch (MessagingException | UnsupportedEncodingException e) {
            String err = e.getMessage();
            err = new String(err.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println(err);
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    String err = e.getMessage();
                    err = new String(err.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    System.out.println(err);
                }
            }
        }
    }
}

Example Email with an Attachment

import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.FileDataSource;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
 
import java.util.Properties;
 
public class SendEmailWithAttachment {
 
    private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
 
    private static final String SMTP_PORT = "465";
 
    public static void main(String[] args) {
 
        // Configure the environment attributes for sending emails.
        final Properties props = new Properties();
        // Identity authentication is required for sending emails through SMTP.
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // If SSL is used, delete the configuration of port 25 and perform the following configuration:
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.port", SMTP_PORT);
        // SMTP account of the sender. Replace username with the SMTP account provided by KooMessage.
        props.put("mail.user", "username");
        // Password required for accessing the SMTP service (set when selecting the sender address on the console). Replace password with the SMTP password provided by KooMessage.
        props.put("mail.password", "password");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.starttls.enable","true");
        // Construct authorization information for SMTP authentication.
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // Username and password.
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // Use the environment attributes and authorization information to create an email session.
        Session mailSession = Session.getInstance(props, authenticator);
        // UUID uuid = UUID.randomUUID();
        // final String messageIDValue = "<" + uuid.toString() + ">";
        // Create an email message.
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            // Customize Message-ID.
            //setHeader("Message-ID", messageIDValue);
            //}
        };
 
        try {
            // Create a message.
            message.setFrom(new InternetAddress("xxxx@xx"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xxxx@xx"));
            message.setSubject("Subject: Test Email with Attachment");
 
            // Create a message body.
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText("This is the email body");
 
            // Create an attachment.
            MimeBodyPart attachmentPart = new MimeBodyPart();
            DataSource source = new FileDataSource("path/to/attachment.txt"); // Attachment path.
            attachmentPart.setDataHandler(new DataHandler(source));
            attachmentPart.setFileName("attachment.txt"); // Attachment name.
 
            // Combine the message body and attachment.
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);
 
            message.setContent(multipart);
 
            // Send the email.
            Transport.send(message);
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback