java

位置:IT落伍者 >> java >> 浏览文章

java实现邮件的发送分享


发布日期:2024年03月05日
 
java实现邮件的发送分享

java实现邮件的发送分享方法如下

public class PopupAuthenticator extends Authenticator{

public PasswordAuthentication getPasswordAuthentication()

{

String username=; //邮箱登录帐号

String pwd = ; //登录密码

return new PasswordAuthentication(usernamepwd)

}

}

public class SendMail {

public static void main(String[] args) {

try {

Authenticator auth = new PopupAuthenticator()

Properties mailProps = new Properties()

//邮件信息验证

mailPropsput(mailsmtphost

mailPropsput(mailsmtpauth true

mailPropsput(username //用户名

mailPropsput(password //密码

Session mailSession = SessiongetDefaultInstance(mailProps auth)

MimeMessage message = new MimeMessage(mailSession)

messagesetFrom(new InternetAddress())//发件人地址

Address toInternetAddress=new InternetAddress(//收件人地址

messagesetRecipient(MessageRecipientTypeTO toInternetAddress)

messagesetSubject(Mail Test //邮件标题

messagesetSentDate(new Date()) // 设置邮件发送日期

MimeMultipart multi = new MimeMultipart()

BodyPart textBodyPart = new MimeBodyPart()

//textBodyPartsetText(Hello World! //邮件内容

multiaddBodyPart(textBodyPart)

messagesetContent(multi)

messagesaveChanges()

//下面代码是发送附件

String fileName = E:/hellotxt; //发送附件的文件路径

MimeBodyPart messageBodyPart = new MimeBodyPart()

messageBodyPartsetText(Hi there is message info //邮件内容

Multipart multipart = new MimeMultipart()

multipartaddBodyPart(messageBodyPart)

messageBodyPart = new MimeBodyPart()

DataSource source = new FileDataSource(fileName)

messageBodyPartsetDataHandler(new DataHandler(source))

messageBodyPartsetFileName(fileName)

multipartaddBodyPart(messageBodyPart)

messagesetContent(multipart)

//推送邮件和附件信息

Transportsend(message)

Systemoutprintln(邮件发送成功

} catch (Exception ex) {

Systemerrprintln(邮件发送失败的原因是 + exgetMessage())

Systemerrprintln(具体错误原因

exprintStackTrace(Systemerr)

}

}

}

               

上一篇:Java FTP客户端类库比较

下一篇:Timer,Quartz和Spring实现作业调度