下面列出了javax.mail.Session#getTransport ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void sendMail()
throws MessagingException, IOException {
Session session = Session.getInstance(getMailProps(), new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
getVal("username"),
getVal("password"));
}
});
session.setDebug(getBoolVal("mail.debug"));
LOG.info("Compiling Mail before Sending");
Message message = createMessage(session);
Transport transport = session.getTransport("smtp");
LOG.info("Connecting to Mail Server");
transport.connect();
LOG.info("Sending Mail");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
LOG.info("Reports are sent to Mail");
clearTempZips();
}
public void sendMail(String receiver, String subject, String message) throws Exception
{
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
properties.setProperty("mail.smtp.auth", "true");//需要验证
Session session = Session.getInstance(properties);
session.setDebug(false);
//邮件信息
Message messgae = new MimeMessage(session);
messgae.setFrom(new InternetAddress(getMailFrom()));//设置发送人
messgae.setText(message);//设置邮件内容
messgae.setSubject(subject);//设置邮件主题
//发送邮件
Transport tran = session.getTransport();
tran.connect(getServerHost(), getServerPort(), getAuthUserName(), getAuthPassword());
tran.sendMessage(messgae, new Address[] { new InternetAddress(receiver) });//设置邮件接收人
tran.close();
Logger.getLogger(this.getClass()).debug(String.format("sent mail to <%s>: %s", receiver, subject));
}
/** */
public void testSendTwoMessagesSameConnection()
throws IOException
{
try
{
MimeMessage[] mimeMessages = new MimeMessage[2];
Properties mailProps = this.getMailProperties(SMTP_PORT);
Session session = Session.getInstance(mailProps, null);
// session.setDebug(true);
mimeMessages[0] = this.createMessage(session, "[email protected]", "[email protected]", "Doodle1", "Bug1");
mimeMessages[1] = this.createMessage(session, "[email protected]", "[email protected]", "Doodle2", "Bug2");
Transport transport = session.getTransport("smtp");
transport.connect("localhost", SMTP_PORT, null, null);
for (MimeMessage mimeMessage : mimeMessages)
{
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
transport.close();
}
catch (MessagingException e)
{
e.printStackTrace();
fail("Unexpected exception: " + e);
}
assertEquals(2, this.server.getMessages().size());
}
private boolean sendMail(String toEmail, String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
msg.setSubject(subject);
msg.setContent(body, "text/html");
Transport transport = session.getTransport();
transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
transport.sendMessage(msg, msg.getAllRecipients());
return true;
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
return false;
}
/**
* Obtain a Transport object from the given JavaMail Session,
* using the configured protocol.
* <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
* @see javax.mail.Session#getTransport(String)
* @see #getSession()
* @see #getProtocol()
*/
protected Transport getTransport(Session session) throws NoSuchProviderException {
String protocol = getProtocol();
if (protocol == null) {
protocol = session.getProperty("mail.transport.protocol");
if (protocol == null) {
protocol = DEFAULT_PROTOCOL;
}
}
return session.getTransport(protocol);
}
public static TransportStrategy newAddressStrategy(final Address address) {
return new TransportStrategy() {
@Override
public Transport getTransport(Session session) throws NoSuchProviderException {
return session.getTransport(address);
}
};
}
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.debug", "true");
prop.setProperty("mail.host", MAIL_SERVER_HOST);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
// 1、创建session
Session session = Session.getInstance(prop);
Transport ts = null;
// 2、通过session得到transport对象
ts = session.getTransport();
// 3、连上邮件服务器
ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);
// 4、创建邮件
MimeMessage message = new MimeMessage(session);
// 邮件消息头
message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
message.setSubject("测试文本邮件"); // 邮件的标题
// 邮件消息体
message.setText("天下无双。");
// 5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
private void sendAuthenticated(EmailProperties emailProperties, Message message, Session session) throws MessagingException {
String host = emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_HOST_KEY);
int port = NumberUtils.toInt(emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_PORT_KEY));
String username = emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_USER_KEY);
String password = emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_PASSWORD_KEY);
Transport transport = session.getTransport("smtp");
try {
transport.connect(host, port, username, password);
transport.sendMessage(message, message.getAllRecipients());
} finally {
transport.close();
}
}
/**
* send email
*
* @throws MessagingException
* @throws Exception
*/
public static int sendMail(String subject, String content, String mails,
String cc) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
// props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator());
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(FROM));
message.addRecipients(Message.RecipientType.TO, getMailList(mails));
message.addRecipients(Message.RecipientType.CC, getMailList(cc));
message.setSubject(subject);
message.setContent(content, "text/html;charset=utf-8");
Transport transport = mailSession.getTransport("smtp");
try {
transport.connect(HOST, USER, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
} finally {
if (transport != null)
transport.close();
}
return 0;
}
/**
* 发送电子邮件
*
* @param smtpHost
* 发信主机
* @param receiver
* 邮件接收者
* @param title
* 邮件的标题
* @param content
* 邮件的内容
* @param sender
* 邮件发送者
* @param user
* 发送者邮箱用户名
* @param pwd
* 发送者邮箱密码
* @throws MessagingException
*/
public static void sendEmail(String smtpHost, String receiver,
String title, String content, String sender, String user, String pwd) throws MessagingException
{
Properties props = new Properties();
props.put("mail.host", smtpHost);
props.put("mail.transport.protocol", "smtp");
// props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动!
props.put("mail.smtp.auth", "true");
Session s = Session.getDefaultInstance(props);
s.setDebug(true);
MimeMessage message = new MimeMessage(s);
// 给消息对象设置发件人/收件人/主题/发信时间
// 发件人的邮箱
InternetAddress from = new InternetAddress(sender);
message.setFrom(from);
InternetAddress to = new InternetAddress(receiver);
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(title);
message.setSentDate(new Date());
// 给消息对象设置内容
BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
// 象(事实上可以存放多个)
mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
message.setContent(mm);// 把mm作为消息对象的内容
message.saveChanges();
Transport transport = s.getTransport("smtp");
transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
public static void main(String[] args) throws Exception {
// Create a Properties object to contain connection configuration information.
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
// Create a Session object to represent a mail session with the specified properties.
Session session = Session.getDefaultInstance(props);
// Create a message with the specified information.
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderAddress,senderName));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses));
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses));
msg.setSubject(subject);
msg.setContent(htmlBody,"text/html");
// Add headers for configuration set and message tags to the message.
msg.setHeader("X-SES-CONFIGURATION-SET", configurationSet);
msg.setHeader("X-SES-MESSAGE-TAGS", tag0);
msg.setHeader("X-SES-MESSAGE-TAGS", tag1);
// Create a transport.
Transport transport = session.getTransport();
// Send the message.
try {
System.out.println("Sending...");
// Connect to Amazon Pinpoint using the SMTP username and password you specified above.
transport.connect(smtpEndpoint, smtpUsername, smtpPassword);
// Send the email.
transport.sendMessage(msg, msg.getAllRecipients());
System.out.println("Email sent!");
}
catch (Exception ex) {
System.out.println("The email wasn't sent. Error message: "
+ ex.getMessage());
}
finally {
// Close the connection to the SMTP server.
transport.close();
}
}
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.debug", "true");
prop.setProperty("mail.host", MAIL_SERVER_HOST);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
// 1、创建session
Session session = Session.getInstance(prop);
// 2、通过session得到transport对象
Transport ts = session.getTransport();
// 3、连上邮件服务器
ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);
// 4、创建邮件
MimeMessage message = new MimeMessage(session);
// 邮件消息头
message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
message.setSubject("测试带附件邮件"); // 邮件的标题
MimeBodyPart text = new MimeBodyPart();
text.setContent("邮件中有两个附件。", "text/html;charset=UTF-8");
// 描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.setSubType("related");
mm.addBodyPart(text);
String[] files = { "D:\\00_Temp\\temp\\1.jpg", "D:\\00_Temp\\temp\\2.png" };
// 添加邮件附件
for (String filename : files) {
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(filename);
mm.addBodyPart(attachPart);
}
message.setContent(mm);
message.saveChanges();
// 5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
@Override
public void run() {
String server = this.readStringArgument("server");
String subject = this.readStringArgument("subject");
String body = this.readStringArgument("body");
String userName = this.readStringArgument("userName");
String password = this.readStringArgument("password");
String to = this.readStringArgument("to");
Integer port = this.readIntArgument("port", 25);
Boolean useTls = this.readBooleanArgument("useTls", true);
String cc = this.readStringArgument("cc", null);
String from = this.readStringArgument("from", "s[email protected]");
try {
Properties prop = System.getProperties();
prop.put("mail.smtp.host", server);
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port", port.toString());
Session session = Session.getInstance(prop, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
if (cc != null) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
}
msg.setSubject(subject);
msg.setText(body);
msg.setSentDate(new Date());
SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
transport.setStartTLS(useTls);
transport.connect(server, userName, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception exc) {
throw new RuntimeException("Failed to send email", exc);
}
}
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object object, BindException exception)
throws Exception {
Admin admin = (Admin) object; //将数据封装起来
System.out.println("表单提交过来时的数据是:"+admin.toString());
if (adminService.addAdmin(admin)) { //调用该方法,将数据持久到数据库中,如果持久化成功,则发送邮件给当前的注册用户
try {
String host = "smtp.qq.com"; // 邮件服务器
String from = "[email protected]"; // 发送邮件的QQ
String authcode = "fgoobvssrkuibjhe"; // 对于QQ的个人邮箱而言,密码使用的是客户端的授权码,而不是用户的邮箱密码
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.setProperty("mail.transport.protocol", "smtp"); // 发送邮件协议名称
props.put("mail.smtp.auth", "true"); // 开启授权
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", authcode);
props.put("mail.smtp.port", "587"); // smtp邮件服务器的端口号,必须是587,465端口调试时失败
props.setProperty("mail.smtp.ssl.enable", "true");
Session session = Session.getDefaultInstance(props,
new GMailAuthenticator("[email protected]",
"fgoobvssrkuibjhe"));
props.put("mail.debug", "true");
MimeMessage message = new MimeMessage(session);
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(admin.getEmail());
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject("注册成功确认邮件");
message.setSentDate(new Date());
//发送的链接包括其写入到数据库中的UUID,也就是链接localhost:8080/Login_Sys/ActivateServlet和UUID的拼接,#连接两个字符串
//获取UUID
System.out.println(adminService.getUUID(admin));
message.setContent("<h1>恭喜你注册成功,请点击下面的连接激活账户</h1><h3><a href='http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate.action?code="+adminService.getUUID(admin)+"'>http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate</a></h3>","text/html;charset=utf-8");
Transport transport = session.getTransport();
transport.connect(host, from, authcode);
message.saveChanges();
Transport.send(message);
transport.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
//封装一个ModelAndView对象,提供转发视图的功能
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", "增加管理员成功");
modelAndView.setViewName("sign_success"); //成功之后跳转到该界面,采用逻辑视图,必须要配置视图解析器
return modelAndView; //该方法一定要返回modelAndView
}
/**
* Send an email.
*
* @param recipient The recipient of the email
* @param subject The subject of the email.
* @param body The body of the email.
* @return true if the email was sent successfully.
*/
public boolean sendMail(final String recipient, final String subject, final String body) {
boolean result = false;
// Create a Properties object to contain connection configuration information.
java.util.Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", getPort());
// Set properties indicating that we want to use STARTTLS to encrypt the connection.
// The SMTP session will begin on an unencrypted connection, and then the client
// will issue a STARTTLS command to upgrade to an encrypted connection.
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
// Create a Session object to represent a mail session with the specified properties.
Session session = Session.getDefaultInstance(props);
// Create a message with the specified information.
MimeMessage msg = new MimeMessage(session);
Transport transport = null;
// Send the message.
try {
msg.setFrom(new InternetAddress(getSender()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setSubject(subject);
msg.setContent(body, "text/plain");
// Create a transport.
transport = session.getTransport();
// Connect to email server using the SMTP username and password you specified above.
transport.connect(getHost(), getSmtpUsername(), getUnobfuscatedSmtpPassword());
// Send the email.
transport.sendMessage(msg, msg.getAllRecipients());
result = true;
} catch (Exception ex) {
LOGGER.error("The email was not sent.", ex);
} finally {
// Close and terminate the connection.
try {
transport.close();
} catch (MessagingException e) {
LOGGER.error("Could not close transport", e);
}
}
return result;
}
@Test
public void testSendTwoMsgsWithLogin() throws Exception {
String serverHost = "localhost";
String from = "[email protected]";
String to = "[email protected]";
String subject = "Test";
String body = "Test Body";
Properties props = System.getProperties();
if (serverHost != null) {
props.setProperty("mail.smtp.host", serverHost);
}
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
if (from != null) {
msg.setFrom(new InternetAddress(from));
} else {
msg.setFrom();
}
InternetAddress.parse(to, false);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setText(body);
msg.setHeader("X-Mailer", "musala");
msg.setSentDate(new Date());
msg.saveChanges();
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect(serverHost, server.getPort(), "ddd", "ddd");
transport.sendMessage(msg, InternetAddress.parse(to, false));
transport.sendMessage(msg, InternetAddress.parse("[email protected]", false));
} finally {
if (transport != null) {
transport.close();
}
}
List<SmtpMessage> emails = this.server.getReceivedEmails();
assertThat(emails, hasSize(2));
SmtpMessage email = emails.get(0);
assertTrue(email.getHeaderValue("Subject").equals("Test"));
assertTrue(email.getBody().equals("Test Body"));
}
public static void main(String args[]) throws Exception {
// read test configuration from test.properties in your classpath
Properties testProps = TestUtil.readProperties();
// get a JavaMail Session object
Session session = Session.getDefaultInstance(testProps, null);
///////// beginning of DKIM FOR JAVAMAIL stuff
// get DKIMSigner object
DKIMSigner dkimSigner = new DKIMSigner(
testProps.getProperty("mail.smtp.dkim.signingdomain"),
testProps.getProperty("mail.smtp.dkim.selector"),
testProps.getProperty("mail.smtp.dkim.privatekey"));
/* set an address or user-id of the user on behalf this message was signed;
* this identity is up to you, except the domain part must be the signing domain
* or a subdomain of the signing domain.
*/
dkimSigner.setIdentity("[email protected]"+testProps.getProperty("mail.smtp.dkim.signingdomain"));
// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
Message msg = new SMTPDKIMMessage(session, dkimSigner);
///////// end of DKIM FOR JAVAMAIL stuff
msg.setFrom(new InternetAddress(testProps.getProperty("mail.smtp.from")));
if (testProps.getProperty("mail.smtp.to") != null) {
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(testProps.getProperty("mail.smtp.to"), false));
}
if (testProps.getProperty("mail.smtp.cc") != null) {
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(testProps.getProperty("mail.smtp.cc"), false));
}
msg.setSubject("DKIM for JavaMail: SimpleExample Testmessage");
msg.setText(TestUtil.bodyText);
// send the message by JavaMail
Transport transport = session.getTransport("smtp");
transport.connect(testProps.getProperty("mail.smtp.host"),
testProps.getProperty("mail.smtp.auth.user"),
testProps.getProperty("mail.smtp.auth.password"));
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
public static void main(String args[]) throws Exception {
// read test configuration from test.properties in your classpath
Properties testProps = TestUtil.readProperties();
// generate string buffered test mail
StringBuffer mimeMail = new StringBuffer();
mimeMail.append("Date: ").append(new MailDateFormat().format(new Date())).append("\r\n");
mimeMail.append("From: ").append(testProps.getProperty("mail.smtp.from")).append("\r\n");
if (testProps.getProperty("mail.smtp.to") != null) {
mimeMail.append("To: ").append(testProps.getProperty("mail.smtp.to")).append("\r\n");
}
if (testProps.getProperty("mail.smtp.cc") != null) {
mimeMail.append("Cc: ").append(testProps.getProperty("mail.smtp.cc")).append("\r\n");
}
mimeMail.append("Subject: ").append("DKIM for JavaMail: MimeMailExample Testmessage").append("\r\n");
mimeMail.append("\r\n");
mimeMail.append(TestUtil.bodyText);
// get a JavaMail Session object
Session session = Session.getDefaultInstance(testProps, null);
///////// beginning of DKIM FOR JAVAMAIL stuff
// get DKIMSigner object
DKIMSigner dkimSigner = new DKIMSigner(
testProps.getProperty("mail.smtp.dkim.signingdomain"),
testProps.getProperty("mail.smtp.dkim.selector"),
testProps.getProperty("mail.smtp.dkim.privatekey"));
/* set an address or user-id of the user on behalf this message was signed;
* this identity is up to you, except the domain part must be the signing domain
* or a subdomain of the signing domain.
*/
dkimSigner.setIdentity("[email protected]"+testProps.getProperty("mail.smtp.dkim.signingdomain"));
// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
Message msg = new SMTPDKIMMessage(session, new ByteArrayInputStream(mimeMail.toString().getBytes()), dkimSigner);
///////// end of DKIM FOR JAVAMAIL stuff
// send the message by JavaMail
Transport transport = session.getTransport("smtp");
transport.connect(testProps.getProperty("mail.smtp.host"),
testProps.getProperty("mail.smtp.auth.user"),
testProps.getProperty("mail.smtp.auth.password"));
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
public boolean sendLog(String host, String userId, String password,
String to, String from, String subject, String message,
File filename) {
boolean success = true;
System.out.println("host: " + host);
System.out.println("userId: " + userId);
// Fortify Mod: commented out clear text password.
// System.out.println("password: " + password);
System.out.println("to: " + to);
System.out.println("from: " + from);
System.out.println("subject: " + subject);
System.out.println("message: " + message);
System.out.println("filename: " + filename.getName());
System.out.println("filename: " + filename.getAbsolutePath());
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, null);
session.setDebug(true);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(message);
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds = new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
// connect to the transport
Transport trans = session.getTransport("smtp");
trans.connect(host, userId, password);
// send the message
trans.sendMessage(msg, msg.getAllRecipients());
// smtphost
trans.close();
} catch (MessagingException mex) {
success = false;
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
}
return success;
}
/**
* return the transport object of the SMTP session
*
* @return the transport object of the SMTP session
* @param session
* the SMTP session
* @throws NoSuchProviderException
* If the provider is not found
*/
protected static Transport getTransport( Session session ) throws NoSuchProviderException
{
return session.getTransport( SMTP );
}