开发者

how to send a mail with data extracted from a database with javamail and smtp?

i want to send emails to an address with a java program (using javamail) via smtp. it actually send the emails to the destination. the problem is the body of the email isn't send fully each time. considering that the body of my mail is extracted from a database. here's my code:

public static void Bmail(Connection conn, String grav, String state)
    {
        Statement stmt;

        try
        {
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

            ResultSet res = stmt.executeQuery("select ID, Time_C from production where name='"+grav +"' and State='"+state+"'");

            while(res.next())
            {                           
                String id=res.getString("1"), tc=res.getString("2"); 
                    testmail smtpMailSend = new testmail();
                String sub="Alert 开发者_如何学Go"+grav+" "+state;
                    String mes=" ID "+id +"\n Stat: "+state +"\n time: "+tc;
                  smtpMailSend.sMail(sub,mes);
             }
         } catch(Exception e)
        {
            e.printStackTrace();
            stmt = null;
        }
    }
public void sMail(String obj,String text)throws MessagingException
{
Properties props = new Properties();
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);
    Message msg = new MimeMessage(session);
    msg.setText(text);
    msg.setContent(text,"text/plain");
    msg.setSubject(obj);
    msg.setFrom(new InternetAddress(d_email));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
    msg.saveChanges();
    Transport transport = session.getTransport("smtps");
    transport.connect(d_host, d_port, d_uname, d_password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    }

so after 2 first record, i've in the mail "ID: 12345" without the time or the state.

well i tried setContent but i still have the same problem. maybe the content type is the cause (i'm putting text/plain)?

thanks for your help


I'm using a DataHandler object in my own implementation of this function, which has been running in production for quite a while. So I first create a data handler passing in the email text and then set that as the message's data handler:

DataHandler messageDataHandler = new DataHandler(notification.getMessage(), "text/plain; charset=\"UTF-8\"");
msg.setDataHandler(messageDataHandler);

You should also specify a text encoding as is done in my example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜