引言
在现代通信中,短信和电子邮件仍然是两种重要的沟通渠道。Infobip API提供了一种强大且灵活的方式来调用这些服务。本篇文章将聚焦于如何利用Infobip API发送短信和邮件。我们将探讨API的基本用法,并提供实用的代码示例,帮助开发者更快地集成这些功能。
主要内容
设置与准备
要使用Infobip API,首先需要拥有一个Infobip账户。可以通过官方网站注册一个免费的试用账号。
使用InfobipAPIWrapper
库来简化API的调用,所有调用均需提供以下参数:
infobip_api_key
:可以在开发者工具中找到API Key。infobip_base_url
:默认为https://api.infobip.com/
。
也可以通过环境变量INFOBIP_API_KEY
和INFOBIP_BASE_URL
来设置这些参数。
发送短信
以下代码展示了如何通过Infobip API发送短信:
from langchain_community.utilities.infobip import InfobipAPIWrapper
# 实例化InfobipAPIWrapper
infobip: InfobipAPIWrapper = InfobipAPIWrapper()
# 发送短信
infobip.run(
to="41793026727",
text="Hello, World!",
sender="Langchain",
channel="sms",
)
# 使用API代理服务提高访问稳定性
发送邮件
类似地,可以使用以下代码来发送电子邮件:
from langchain_community.utilities.infobip import InfobipAPIWrapper
# 实例化InfobipAPIWrapper
infobip: InfobipAPIWrapper = InfobipAPIWrapper()
# 发送电子邮件
infobip.run(
to="test@example.com",
sender="test@example.com",
subject="example",
body="example",
channel="email",
)
# 使用API代理服务提高访问稳定性
代码示例
除了直接发送短信和邮件,Infobip还可以在一个代理工具中使用,以下示例展示了如何在一个Agent中集成发送邮件的功能:
from langchain import hub
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_community.utilities.infobip import InfobipAPIWrapper
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import StructuredTool
from langchain_openai import ChatOpenAI
class EmailInput(BaseModel):
body: str = Field(description="Email body text")
to: str = Field(description="Email address to send to.")
sender: str = Field(description="Email address to send from.")
subject: str = Field(description="Email subject")
channel: str = Field(description="Email channel, must be 'email'")
infobip_api_wrapper: InfobipAPIWrapper = InfobipAPIWrapper()
infobip_tool = StructuredTool.from_function(
name="infobip_email",
description="Send Email via Infobip.",
func=infobip_api_wrapper.run,
args_schema=EmailInput,
)
tools = [infobip_tool]
agent = create_openai_functions_agent(ChatOpenAI(), tools, hub.pull("langchain-ai/openai-functions-template"))
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke(
{
"input": "Hi, can you please send me an example of Python recursion to my email email@example.com"
}
)
常见问题和解决方案
- 网络限制:由于某些地区网络限制导致API无法访问,建议使用API代理服务以提高访问的稳定性。
- 认证问题:确保密钥和URL设置正确,可以通过环境变量统一管理这些配置。
总结和进一步学习资源
通过本篇文章,我们深入了解了Infobip API的基本用法,并通过代码示例展示了如何进行短信和邮件的发送。对于进一步学习,可以参考官方文档及其丰富的API功能。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—