java代码实现发送邮件

使用java代码实现发送邮件。

首先,在eclipse中要导入jar包,右击你的项目,选择“Build Path”,子菜单选择“Configure Build Path”,弹出“Properties”属性页,选择“Libraries”选项卡,在选项卡内容右侧选择“Add External JARs...”按钮,选择你要导入的本地的Jar包,ok!

然后代码实现:  亲测可用..............

package pack;


import java.util.Properties;


import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class SendMail {

private String host = "";
private String user = "";
private String pwd = "";
private String from = "";
private String to = "";
private String subject = "";

public void setAddress(String from,String to,String subject){
this.from = from;
this.to = to;
this.subject = subject;

}

public void send(String txt){
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth","false");

Session session = Session.getDefaultInstance(props);
session.setDebug(true);

MimeMessage message = new MimeMessage(session);

try {
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);

Multipart multipart = new MimeMultipart();

BodyPart contentPart = new MimeBodyPart();
contentPart.setText(txt);
multipart.addBodyPart(contentPart);

message.setContent(multipart);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host,user,pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();

} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static void main(String[] args){
SendMail sendmail = new SendMail(); 
sendmail.setAddress("@126.com","qq.com","标题");
sendmail.send("测试正文内容");
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值