Javamail API - How do you change setFrom to whatever you want?

后端 未结 4 1681
孤独总比滥情好
孤独总比滥情好 2021-01-12 06:38

How do I change the setFrom() method to whatever I want? I can send e-mails through my gmail accoutn and change the setFrom text, but it shows my username for t

4条回答
  •  无人共我
    2021-01-12 06:58

    Here is the full code You can use the following code. This is working Fine for me

    class SendMail {
    public static void main(String[] args) {
        System.out.println("In side main()---------------------");
    
        Properties props = new Properties();
    
    
        props.put("mail.smtp.host", "hostname");
        props.put("mail.smtp.port", "port");//
    
        props.put("mail.smtp.socketFactory.port", "port");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
    
    
    
        props.put("mail.smtp.auth", "true");
    
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
    
                    protected PasswordAuthentication getPasswordAuthentication() {
                        System.out
                                .println("In side getPasswordAuthentication------------------And Before returning PasswordAuthentication");
                        return new PasswordAuthentication("from@gmail.com",
                                "password");
    
                    }
    
                });
        System.out
                .println("mail and password has been sent********************");
        try {
            System.out
                    .println("we are  in try{} block.................................");
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("to@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear User," + "\n\n This is testing only!");
    
            Transport.send(message);
    
            System.out
                    .println("Mail has been sent successfully..........................");
    
        } catch (MessagingException e) {
            System.out.println("we are in catch block...................");
            e.printStackTrace();
    
        }
    }
    

    }

提交回复
热议问题