java 程序自动写邮件_后台自动发邮件--java代码

import java.util.Properties;

import javax.mail.Message;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class SendMail {

/**

* @param args

*/

public static void main(String[] args) {

Properties props = System.getProperties();

// 设置smtp服务器

props.setProperty("mail.smtp.host", "smtp.126.com");

// 现在的大部分smpt都需要验证了

props.put("mail.smtp.auth", "true");

Session s = Session.getInstance(props);

// 为了查看运行时的信息

s.setDebug(true);

// 由邮件会话新建一个消息对象

MimeMessage message = new MimeMessage(s);

try {

// 发件人

InternetAddress from = new InternetAddress("fasongren@126.com");

message.setFrom(from);

// 收件人

InternetAddress to = new InternetAddress("jieshouren@163.com");

message.setRecipient(Message.RecipientType.TO, to);

// 邮件标题

message.setSubject("test");

String content = "测试内容";

// 邮件内容,也可以使纯文本"text/plain"

message.setContent(content, "text/html;charset=GBK");

/****下面代码是发送附件******

String fileName = "d://hello.txt";

MimeBodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setText("Hi");

Multipart multipart = new MimeMultipart();

multipart.addBodyPart(messageBodyPart);

messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(fileName);

messageBodyPart.setDataHandler(new DataHandler(source));

messageBodyPart.setFileName(fileName);

multipart.addBodyPart(messageBodyPart);

message.setContent(multipart);*/

message.saveChanges();

Transport transport = s.getTransport("smtp");

// smtp验证,就是你用来发邮件的邮箱用户名密码

transport.connect("smtp.126.com", "username", "password");

// 发送

transport.sendMessage(message, message.getAllRecipients());

transport.close();

} catch (Exception e) {

e.printStackTrace();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值