这是我的代码。代码是groovy。
//send email
def host = "smtp.gmail.com"
def props = new Properties()
props.put "mail.smtps.auth", "true"
def session = Session.getDefaultInstance(props, null)
def msg = new MimeMessage(session)
msg.setSubject subject
msg.setText messageText
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, to))
def transport = session.getTransport "smtps"
transport.connect(host, username, password)
transport.sendMessage(msg, msg.getAllRecipients())
transport.close()
//fetch emails
def host = "imap.gmail.com"
def port = "993"
Properties props = new Properties()
props.setProperty("mail.store.protocol", "imap")
props.setProperty("mail.imap.host", host)
props.setProperty("mail.imap.port", port)
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
def session = Session.getDefaultInstance(props, null)
def store = session.getStore("imap")
store.connect(host, username, password)
def inbox = store.getFolder("INBOX")
inbox.open(Folder.READ_ONLY)
def messages = inbox.getMessages()
连接imap store时此代码失败。
javax.mail.MessagingException: * BYE Cannot connect to IMAP server
如果我跳过使用smtp发送电子邮件,则提取部分可以正常工作。发送和提取邮件都使用相同的Gmail帐户。我想会话或gmail限制可能会有一些问题。发送电子邮件也正常。