Java Mail 邮件 demo

package cn.com.cloud.utils;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 * 邮件
 * @author 李海云
 * @date 2012-02-23
 * @email CloudComputing.cc@gmail.com 
 */
public class TestMail {
	public static void main(String[] args) throws MessagingException {
		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		Session session = Session.getInstance(props);
		session.setDebug(true);
		
		Message msg = new MimeMessage(session);
		msg.setSubject("你好subject");
		msg.setText("天气晴朗text");
		msg.setFrom(new InternetAddress("your username@qq.com"));//发件人address

		Transport transport = session.getTransport();
		//发送者	1连接服务器 2端口号 3用户名 4密码
		transport.connect("smtp.qq.com", 25, "your username", "your password");
		//发送目标
		transport.sendMessage(msg,
				new Address[]{new InternetAddress("target username@qq.com")});
		transport.close();
	}
}

 
以下是一个简单的Java发送邮件的示例代码: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendMailDemo { public static void main(String[] args) { // 发件人邮箱地址 String from = "example@163.com"; // 收件人邮箱地址 String to = "example@gmail.com"; // SMTP服务器地址 String host = "smtp.163.com"; // 发件人邮箱账号和密码 final String username = "example@163.com"; final String password = "password"; // 创建邮件的属性对象 Properties props = new Properties(); // 设置SMTP服务器地址和端口号 props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // 需要认证 props.put("mail.smtp.auth", "true"); // 使用SSL加密连接 props.put("mail.smtp.ssl.enable", "true"); // 创建会话对象 Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // 创建邮件对象 Message message = new MimeMessage(session); // 邮件发送者 message.setFrom(new InternetAddress(from)); // 邮件接收者 message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 邮件主题 message.setSubject("Test Email"); // 邮件内容 message.setText("This is a test email sent from Java!"); // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用了JavaMail API和JavaMail Session API,以及SMTP协议和SSL加密连接来发送邮件。在程序中,我们需要提供发件人邮箱地址、收件人邮箱地址、SMTP服务器地址、发件人邮箱账号和密码等信息,然后连接到SMTP服务器并发送邮件。最后,我们可以检查邮件是否成功发送并进行相应的处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值