Home Java javaTutorial Detailed explanation of the steps to send email in Java

Detailed explanation of the steps to send email in Java

Sep 23, 2017 am 10:19 AM
email java Detailed explanation

The following editor will bring you an article on the general steps for sending emails in Java (explanation with examples). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

General steps for sending email in java

##1. Introduce the jar package of javamail:

2. Create a test class to write the content of the email to be sent to the local computer to see if the content can be written:


public static void main(String[] args) throws Exception { 
  // 1. 创建一封邮件 
  Properties props = new Properties();        // 用于连接邮件服务器的参数配置(发送邮件时才需要用到) 
  Session session= Session.getDefaultInstance(props); // 根据参数配置,创建会话对象(为了发送邮件准备的) 
  MimeMessage message = new MimeMessage(session);   // 创建邮件对象 
 
  /* 
   * 也可以根据已有的eml邮件文件创建 MimeMessage 对象 
   * MimeMessage message = new MimeMessage(session, new FileInputStream("MyEmail.eml")); 
   */
 
  // 2. From: 发件人 
  //  其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码 
  //  真正要发送时, 邮箱必须是真实有效的邮箱。 
  message.setFrom(new InternetAddress("123456@qq.com", "USER_AA", "UTF-8")); 
 
  // 3. To: 收件人 
  message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("123654@qq.com", "USER_CC", "UTF-8")); 
  //  To: 增加收件人(可选) 
  //message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("dd@receive.com", "USER_DD", "UTF-8")); 
  //  Cc: 抄送(可选) 
  //message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("ee@receive.com", "USER_EE", "UTF-8")); 
  //  Bcc: 密送(可选) 
  //message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("ff@receive.com", "USER_FF", "UTF-8")); 
 
  // 4. Subject: 邮件主题 
  message.setSubject("TEST邮件主题", "UTF-8"); 
 
  // 5. Content: 邮件正文(可以使用html标签) 
  message.setContent("TEST这是邮件正文。。。", "text/html;charset=UTF-8"); 
 
  // 6. 设置显示的发件时间 
  message.setSentDate(new Date()); 
 
  // 7. 保存前面的设置 
  message.saveChanges(); 
 
  // 8. 将该邮件保存到本地 
  OutputStream out = new FileOutputStream("D://MyEmail.eml"); 
  message.writeTo(out); 
  out.flush(); 
  out.close(); 
}
Copy after login

3. Create a class for sending emails: send emails from one email account to another email account


// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) 
  // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), 
  //   对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 
  public static String myEmailAccount = "123456@qq.com"; 
  public static String myEmailPassword = "abcdefg"; 
 
  // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com 
  // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com 
  public static String myEmailSMTPHost = "smtp.qq.com"; 
 
  // 收件人邮箱(替换为自己知道的有效邮箱) 
  public static String receiveMailAccount = "123654@qq.com"; 
 
  public static void main(String[] args) throws Exception { 
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置 
    Properties props = new Properties();          // 参数配置 
    props.setProperty("mail.transport.protocol", "smtp");  // 使用的协议(JavaMail规范要求) 
    props.setProperty("mail.smtp.host", myEmailSMTPHost);  // 发件人的邮箱的 SMTP 服务器地址 
    props.setProperty("mail.smtp.auth", "true");      // 需要请求认证 
 
    // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), 
    //   如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, 
    //   打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 
    /* 
    // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, 
    //         需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, 
    //         QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) 
    final String smtpPort = "465"; 
    props.setProperty("mail.smtp.port", smtpPort); 
    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
    props.setProperty("mail.smtp.socketFactory.port", smtpPort); 
    */
 
    // 2. 根据配置创建会话对象, 用于和邮件服务器交互 
    Session session = Session.getDefaultInstance(props); 
    session.setDebug(true);                 // 设置为debug模式, 可以查看详细的发送 log 
 
    // 3. 创建一封邮件 
    MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount); 
 
    // 4. 根据 Session 获取邮件传输对象 
    Transport transport = session.getTransport(); 
 
    // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 
    // 
    //  PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, 
    //      仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 
    //      类型到对应邮件服务器的帮助网站上查看具体失败原因。 
    // 
    //  PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: 
    //      (1) 邮箱没有开启 SMTP 服务; 
    //      (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; 
    //      (3) 邮箱服务器要求必须要使用 SSL 安全连接; 
    //      (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; 
    //      (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 
    // 
    //  PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 
    transport.connect(myEmailAccount, myEmailPassword); 
 
    // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 
    transport.sendMessage(message, message.getAllRecipients()); 
 
    // 7. 关闭连接 
    transport.close(); 
  }
Copy after login

4. Define a method of creating a text content email:


public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception { 
    // 1. 创建一封邮件 
    MimeMessage message = new MimeMessage(session); 
 
    // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称) 
    message.setFrom(new InternetAddress(sendMail, "sss", "UTF-8")); 
 
    // 3. To: 收件人(可以增加多个收件人、抄送、密送) 
    message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "zzz", "UTF-8")); 
 
    // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题) 
    message.setSubject("开会通知", "UTF-8"); 
 
    // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容) 
    message.setContent("今天下午3点会议室开会。", "text/html;charset=UTF-8"); 
 
    // 6. 设置发件时间 
    message.setSentDate(new Date()); 
 
    // 7. 保存设置 
    message.saveChanges(); 
 
    return message; 
  }
Copy after login

5. After personal experience It is completely possible to send emails. What you need to pay special attention to is:

#The email sender’s email address must have an SMTP client enabled. If the sender’s email address is not enabled, it is necessary to send the email. unsuccessful.

The above is the detailed content of Detailed explanation of the steps to send email in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles